Stock charts: CSV data loading (load_csv/set_series/clear/populate)

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).
This commit is contained in:
cnmcdee committed 2026-12-02 09:55:14 +00:00
1 parent bfb366c083
commit 11493b5f22
6 files changed
+1277 -68

No files matched your search

+1
View File
@@ -114,6 +114,7 @@ tests/ unittest suites, one file per module area
tools/ property-table generators (gen_props.py, gen_props_phase6.py)
docs/
architecture.md design decisions, phase plan, final module layout
stock-charts-data.md stock charts: data model, CSV format, set_series/load_csv API
screenshots/ fresh Xvfb screenshots of the current UI
```
+249
View File
@@ -0,0 +1,249 @@
# Stock chart widgets: plotting your own data
The 24 Stock Market widgets that plot a data series -- candlesticks,
line/area/baseline charts, volume, VWAP, OBV, Renko, Heikin-Ashi, and
the multi-symbol comparison charts -- all draw from the same data
model, and all take real data the same way: `set_series()` for bars
you already hold in Python, or `load_csv()` for an OHLCV file.
The other 13 Stock widgets are pure drawing tools (Trendline,
HorizontalLine, VerticalLine, Rectangle, Ellipse, Arrow,
FibRetracement, FibExtension, ParallelChannel, Pitchfork,
MeasureTool, Brush, TextAnnotation). They take no data input -- they
draw over the candle chart using anchor props -- so they are out of
scope here, except for one note: because they render the same candle
background, a series you load into a tool widget *does* change what
its background shows.
## Data model
A bar is a 5-tuple of floats:
```python
(open, high, low, close, volume)
```
That is the whole model. There is no timestamp on a bar: the x-axis
plots bar index (0, 1, 2, ...), like the C demo. The CSV loader
parses and validates the date column but does not store it (see
below).
## Template data: what ships inside each widget
With no data fed in, every chart renders the built-in deterministic
demo series, so the designer and the generated example draw
immediately:
- `lightgui.xframe.stock.demo_series(n=250, seed=42)` -- an exact
port of C `xframe::make_seeded_series(250)` (StockData.h): a
xorshift64* random walk starting at 100.0. Same `(n, seed)` gives
identical bars on every run. Every bar satisfies
`high >= max(open, close)` and `low <= min(open, close)`.
- `DEMO_SERIES` (250 bars, seed 42) is the primary series;
`DEMO_SERIES_2` (seed 43) and `DEMO_SERIES_3` (seed 44) are the
second/third symbols for the multi-symbol charts.
Derived series are rebuilt from whatever series the widget currently
holds -- Heikin-Ashi candles, Renko bricks, VWAP, OBV, accumulation/
distribution, money flow, rolling correlation, indexed and ratio/
spread lines -- exactly as C `set_series` rebuilds them. Loading
your own data therefore changes the derived charts too, not just
the candles.
| Widget | Series it plots |
| --- | --- |
| CandlestickChart, HollowCandles, OHLCBarChart, LineChart, AreaChart, BaselineChart, VolumeBars, VolumeCandles, VolumeProfile | primary |
| HeikinAshi, Renko, VWAP, OBVChart, AccumulationDistribution, MoneyFlowChart | primary (derived: HA candles / bricks / VWAP / OBV / A/D / flow) |
| Price (StockPriceLabel) | primary (last close + change vs previous close) |
| CorrelationView, IndexedComparison, OverlayChart, RatioChart, SpreadChart | primary + 2nd |
| MultiSymbolChart, RelativePerformance, SectorComparison | primary + 2nd + 3rd |
## API
All of this lives on `StockWidget` (`lightgui/xframe/stock.py`),
the Python port of the C `set_series` API plus a CSV loader the C
widgets do not have:
```python
widget.set_series(bars, which=1) # replace a series slot
widget.get_series(which=1) # bars currently plotted (a copy)
widget.populate(bars, which=1) # alias for set_series
widget.clear(which=0) # empty slot(s); 0 = all three
widget.add_point(bar) # append one bar, return new count
widget.load_csv(path, which=1) # load an OHLCV CSV, return bar count
widget.item_count(which=1) # number of bars plotted
```
- `bars` is a list of `(open, high, low, close, volume)` tuples/lists
of numbers, or dicts with `open`/`high`/`low`/`close`/`volume`
keys. Bad bars raise `ValueError` (wrong length, non-numeric,
`high` below open/close, `low` above open/close, negative volume).
- `set_series(None)` reverts a slot to the built-in demo series.
`set_series` also resets the view window (`view-first` /
`view-count` props), like C `set_series`.
- `clear()` empties the series; the widget then draws a "No data --
call set_series() or load_csv()" placeholder instead of a chart
until `populate()` / `set_series()` refills it (or
`set_series(None)` restores the demo). `clear(which=2)` empties
only the second symbol.
- `add_point()` appends to the primary series. If no own series was
set yet it starts a fresh series -- it does NOT extend the demo
series.
- Series data is runtime state only: it is NOT saved in `.fdj`
files, and it has no Inspector row (the C generator SKIPs it). A
project reloaded in the designer shows the demo series again
until the generated program loads its data.
## CSV format
`load_csv(source)` -- `source` is a path or a file-like object --
reads the file with the stdlib `csv` module and returns a list of
bars. `StockWidget.load_csv(path)` loads it straight into the
widget.
```
date,open,high,low,close,volume
2026-01-05,100.00,100.18,98.80,99.40,530827
2026-01-06,99.40,99.94,99.30,99.58,1196376
...
```
- **Columns:** `date,open,high,low,close,volume`, in that order when
there is no header.
- **Header row (optional, auto-detected):** when the first row names
the columns, they are matched by name -- case-insensitively, in
any order, and extra columns (e.g. `Adj Close`) are ignored.
Aliases: `timestamp` / `time` / `datetime` for date, `o` / `h` /
`l` / `c` for open/high/low/close, `vol` / `v` for volume.
- **Dates:** `YYYY-MM-DD`, `YYYY/MM/DD`, `DD-MM-YYYY`, an ISO
datetime (`YYYY-MM-DD HH:MM:SS`), or epoch seconds. A bad date
raises `ValueError` naming the row. Dates are validated, not
stored and not plotted -- the x-axis is bar index.
- **Validation:** every row must have all six columns, all five
prices/volumes must parse as numbers, `high >= max(open, close)`,
`low <= min(open, close)`, `volume >= 0`. A violation raises
`ValueError` naming the row (a high-below-close error also says
"check the column order", the usual cause). A file with no data
rows raises `ValueError`. On any error `load_csv` leaves the
widget's previous series untouched.
- A ready-made file lives in the repo:
`tests/data/ohlcv_30.csv` -- 30 weekday bars, 2026-01-05 to
2026-02-13, opening at 100.00 and closing at 95.71.
## Working example
A complete program: one window, one candlestick chart, CSV data.
Run it from the repo root:
```python
#!/usr/bin/env python3
"""Plot an OHLCV CSV file in a StockCandlestickChart.
Run from the repo root:
PYTHONPATH=/opt/lightgui_python python3 stock_csv_example.py \
tests/data/ohlcv_30.csv
"""
import sys
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk, Gtk # noqa: E402
from lightgui.xframe.core import create # noqa: E402
def main(csv_path):
window = Gtk.Window(title="StockCandlestickChart - CSV data")
window.set_default_size(640, 400)
window.connect("destroy", Gtk.main_quit)
area = Gtk.DrawingArea()
area.set_hexpand(True)
area.set_vexpand(True)
window.add(area)
widget = create("StockCandlestickChart", "StockCandlestickChart_001",
16, 16, 608, 368)
n = widget.load_csv(csv_path)
print("loaded %d bars from %s" % (n, csv_path))
print("last close: %.2f" % widget.get_series()[-1][3])
def _on_draw(area, cr):
cr.set_source_rgb(1, 1, 1)
cr.paint()
widget.draw(cr)
return False
area.connect("draw", _on_draw)
window.show_all()
Gtk.main()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1
else "tests/data/ohlcv_30.csv"))
```
In a program the designer generated, add one line in
`_build_widgets()`, right after the widget is created:
```python
widget = create('StockCandlestickChart', 'StockCandlestickChart_001', 16, 16, 200, 90)
widget.load_csv('tests/data/ohlcv_30.csv')
```
Multi-symbol charts take one file per symbol:
```python
widget.load_csv('aapl.csv') # primary series
widget.load_csv('msft.csv', which=2) # second symbol
widget.load_csv('goog.csv', which=3) # third symbol (3-symbol charts)
```
Or feed bars directly, without a file:
```python
widget.set_series([
(100.0, 100.18, 98.80, 99.40, 530827.0),
(99.40, 99.94, 99.30, 99.58, 1196376.0),
])
widget.add_point((99.58, 100.00, 97.81, 97.92, 558790.0))
```
## Clear / populate workflow
```python
widget.clear() # empty: placeholder is drawn
widget.populate(new_bars) # refill (== set_series(new_bars))
widget.set_series(None) # or: back to the demo series
```
## Limits
- Dates are validated but never plotted: the x-axis is bar index,
so two files with the same prices but different dates render
identically.
- A series is runtime state: it is not saved in `.fdj` files and
does not survive a designer reload -- the generated program must
load its data on start.
- `set_series` resets the view window (`view-first`/`view-count`).
Window the visible bars afterwards with those props if needed.
- A one-bar series draws (Price shows a flat change -- no previous
close). An empty series draws the no-data placeholder.
- The CSV loader is Python-only: the C and Rust widgets have
`set_series` but no CSV loader.
## Tests and screenshots
- `python3 -m unittest tests.test_stock_csv` -- 27 tests: CSV parsing
(header / no-header / shuffled columns / date formats / every
`ValueError` path), the series API, and headless Cairo renders of
all 24 chart kinds with CSV data, including a check that the CSV
render differs from the template render.
- `python3 tools/stock_csv_shots.py` -- re-renders every in-scope
chart under Xvfb with `tests/data/ohlcv_30.csv` loaded (same
render path as the pythondoc sweep) and reports the ImageMagick
RMSE of each shot against its template-data golden: 9-35% across
the 24 widgets, i.e. the CSV data is visibly what is plotted.
Shots land in `/opt/lightgui-docs/pythondoc/work/csv-shots/`.
+435 -68
View File
@@ -10,8 +10,28 @@ Demo data: every chart renders from ``demo_series()``, an exact port
of C ``xframe::make_seeded_series(250)`` (StockData.h) -- a
deterministic xorshift64* random walk starting at 100.0 -- so chart
colours are visible in the designer without series data, like C
(seeds 250). ``set_series`` is a data source, not a scalar prop, so
it has no Inspector row (the C generator SKIPs it).
(seeds 250).
Feeding real data: each widget holds up to three series slots
(primary + two extra for the multi-symbol charts) via
``StockWidget.set_series(bars, which=1)`` -- the Python port of C
``set_series`` -- plus ``get_series``, ``add_point``, ``clear`` /
``populate`` and ``load_csv``. ``load_csv`` reads a
``date,open,high,low,close,volume`` file with the stdlib ``csv``
module (see ``docs/stock-charts-data.md`` for the format spec).
``set_series`` is a data source, not a scalar prop, so it has no
Inspector row (the C generator SKIPs it). Series data is runtime
state only: it is NOT saved in .fdj files, so a project reloaded in
the designer shows the demo series again until the generated program
loads its data.
Template data, per widget: the primary series is ``DEMO_SERIES``
(250 bars, seed 42); the multi-symbol charts also use
``DEMO_SERIES_2`` (seed 43) and ``DEMO_SERIES_3`` (seed 44) as their
second/third symbols. Derived series (Heikin-Ashi, Renko, VWAP, OBV,
A/D, Money Flow, correlation, indexed, ratio, spread) are rebuilt
from whatever series the widget currently holds, exactly as C
``set_series`` rebuilds them.
Short-plot guard (the Rust plot.rs:250 clamp class): Rust clamps a
marker y into ``[area.y + 8, area.y + area.h - 8]``; when the plot is
@@ -35,6 +55,8 @@ Other tools draw a centred default when they have 0 anchors so the
widget still reads as its kind in the palette.
"""
import csv
import datetime
import math
from lightgui.xframe.core import (
@@ -107,6 +129,232 @@ def demo_series(n=_DEMO_N, seed=42):
DEMO_SERIES = demo_series()
DEMO_SERIES_2 = demo_series(seed=43)
DEMO_SERIES_3 = demo_series(seed=44)
_DEMO_BY_SLOT = (DEMO_SERIES, DEMO_SERIES_2, DEMO_SERIES_3)
# --- CSV loading -----------------------------------------------------------
# Format: date,open,high,low,close,volume -- one bar per row. The
# header row is optional (auto-detected); with a header, columns are
# matched by name (order-independent, extra columns ignored), without
# one they are positional. The date is parsed and validated but NOT
# stored: bars are (open, high, low, close, volume) 5-tuples, the same
# model demo_series() returns, and the x-axis plots bar index, not
# dates (like the C demo, whose axis is also index-based).
_CSV_COLUMNS = ("date", "open", "high", "low", "close", "volume")
_CSV_ALIASES = {
"date": ("date", "timestamp", "time", "datetime"),
"open": ("open", "o"),
"high": ("high", "h"),
"low": ("low", "l"),
"close": ("close", "c"),
"volume": ("volume", "vol", "v"),
}
_CSV_DATE_FORMATS = (
"%Y-%m-%d", "%Y/%m/%d", "%d-%m-%Y", "%Y-%m-%d %H:%M:%S",
"%Y-%m-%dT%H:%M:%S",
)
def _parse_csv_date(text, row_no):
"""Parse a CSV date cell; raises ValueError naming the row."""
text = text.strip()
if not text:
raise ValueError("CSV row %d: empty date" % row_no)
try: # epoch seconds (int or float, e.g. 1767225600)
epoch = float(text)
if 946684800 <= epoch <= 4102444800: # 2000-01-01 .. 2100-01-01
return datetime.datetime.fromtimestamp(
epoch, datetime.timezone.utc)
except (ValueError, OverflowError, OSError):
pass
for fmt in _CSV_DATE_FORMATS:
try:
return datetime.datetime.strptime(text, fmt)
except ValueError:
continue
raise ValueError(
"CSV row %d: unparsable date %r (expected YYYY-MM-DD, "
"YYYY/MM/DD, DD-MM-YYYY, an ISO datetime, or epoch seconds)"
% (row_no, text))
def _parse_csv_float(text, row_no, column):
try:
return float(text)
except (TypeError, ValueError):
raise ValueError("CSV row %d: %s is not a number: %r"
% (row_no, column, text))
def _check_bar(bar, row_no):
"""Validate one (open, high, low, close, volume) bar."""
open_v, high, low, close, volume = bar
if high < max(open_v, close):
raise ValueError(
"CSV row %d: high %.2f is below open/close (%.2f/%.2f) -- "
"check the column order" % (row_no, high, open_v, close))
if low > min(open_v, close):
raise ValueError(
"CSV row %d: low %.2f is above open/close (%.2f/%.2f) -- "
"check the column order" % (row_no, low, open_v, close))
if volume < 0:
raise ValueError("CSV row %d: negative volume %.2f"
% (row_no, volume))
return bar
def _validate_bars(bars, what="series"):
"""Normalise *bars* to a list of float (o, h, l, c, v) tuples.
Accepts 5-tuples/lists of numbers, or dicts with open/high/low/
close/volume keys. Raises ValueError on a malformed bar.
"""
if bars is None:
return None
out = []
for i, bar in enumerate(bars):
if isinstance(bar, dict):
try:
vals = tuple(float(bar[k]) for k in
("open", "high", "low", "close", "volume"))
except (KeyError, TypeError, ValueError):
raise ValueError(
"%s bar %d: need open/high/low/close/volume, got %r"
% (what, i, bar))
else:
try:
vals = tuple(float(v) for v in bar)
except (TypeError, ValueError):
raise ValueError(
"%s bar %d: need 5 numbers, got %r" % (what, i, bar))
if len(vals) != 5:
raise ValueError(
"%s bar %d: need 5 numbers, got %d"
% (what, i, len(vals)))
out.append(_check_bar(vals, i + 1))
return out
def _header_map(first_row):
"""Column-name -> index for a header row, or None if not a header.
A row counts as a header when its cells (lowercased, stripped)
cover every required column by name/alias. Unknown extra cells
(e.g. Adj Close) are ignored.
"""
cells = [str(c).strip().lower() for c in first_row]
mapping = {}
for column, aliases in _CSV_ALIASES.items():
for alias in aliases:
if alias in cells:
mapping[column] = cells.index(alias)
break
else:
return None
return mapping
def load_csv(source):
"""Load OHLCV bars from a CSV file.
*source* is a path (str / os.PathLike) or a file-like object
opened for text. Returns a list of (open, high, low, close,
volume) float tuples, in file order.
Expected columns: ``date,open,high,low,close,volume``. A header
row is optional: when the first row names the columns (matched
case-insensitively, aliases ``timestamp``/``time`` for date,
``o``/``h``/``l``/``c``/``vol``/``v`` accepted) the columns are
read by name in any order and extra columns are ignored;
otherwise the row must have exactly those six columns in order.
Dates accept ``YYYY-MM-DD``, ``YYYY/MM/DD``, ``DD-MM-YYYY``, an
ISO datetime, or epoch seconds; the date is validated but not
stored (bars carry no timestamp, and the x-axis is bar index).
Raises ValueError naming the offending row on bad data, and
ValueError when the file has no data rows.
"""
close_after = False
if hasattr(source, "read"):
handle = source
else:
handle = open(source, "r", encoding="utf-8-sig", newline="")
close_after = True
try:
rows = [r for r in csv.reader(handle)
if r and any(str(c).strip() for c in r)]
finally:
if close_after:
handle.close()
if not rows:
raise ValueError("CSV: no rows found")
mapping = _header_map(rows[0])
if mapping is None:
# A first row that names *some* columns but not all of them is
# a broken header, not data -- say so instead of failing on
# "open is not a number: 'open'".
first_cells = {str(c).strip().lower() for c in rows[0]}
known = {a for aliases in _CSV_ALIASES.values() for a in aliases}
if first_cells & known:
missing = [c for c in _CSV_COLUMNS
if not (set(_CSV_ALIASES[c]) & first_cells)]
raise ValueError(
"CSV header names only some columns; missing: %s"
% ", ".join(missing))
for i, r in enumerate(rows):
if len(r) != 6:
raise ValueError(
"CSV row %d: expected 6 columns "
"(date,open,high,low,close,volume), got %d"
% (i + 1, len(r)))
data_rows = rows[1:] if mapping is not None else rows
bars = []
for offset, row in enumerate(data_rows):
row_no = offset + (2 if mapping is not None else 1)
if mapping is not None:
try:
cells = {c: row[mapping[c]] for c in _CSV_COLUMNS}
except IndexError:
raise ValueError(
"CSV row %d: short row, expected %d columns, got %d"
% (row_no, max(mapping.values()) + 1, len(row)))
else:
cells = dict(zip(_CSV_COLUMNS, row))
_parse_csv_date(cells["date"], row_no)
bar = tuple(_parse_csv_float(cells[c], row_no, c)
for c in ("open", "high", "low", "close", "volume"))
bars.append(_check_bar(bar, row_no))
if not bars:
raise ValueError("CSV: no data rows found")
return bars
def _bars(widget, which=1):
"""The OHLCV bars a draw function should plot for *widget*.
Slot *which* (1, 2 or 3): the widget's own series when one was
set with ``set_series`` (an empty list stays empty -- a cleared
widget draws the no-data placeholder), else the built-in demo
series for that slot (``DEMO_SERIES`` / ``_2`` / ``_3``).
"""
if not 1 <= which <= 3:
raise ValueError("series slot must be 1, 2 or 3, got %r" % (which,))
own = getattr(widget, "_series", None) or (None, None, None)
if own[which - 1] is not None:
return own[which - 1]
return _DEMO_BY_SLOT[which - 1]
# Kinds that plot two or three series (primary + extras); used by
# StockWidget._draw to show the no-data placeholder when any series
# a kind needs is empty.
_MULTI_KINDS = frozenset((
"CorrelationView", "IndexedComparison", "MultiSymbolChart",
"OverlayChart", "RatioChart", "RelativePerformance",
"SectorComparison", "SpreadChart",
))
_THREE_SERIES_KINDS = frozenset((
"MultiSymbolChart", "RelativePerformance", "SectorComparison",
))
# Palette kinds (stock.py covers the 37 Stock* registry names).
STOCK_KINDS = frozenset((
@@ -456,7 +704,7 @@ def _line_through(cr, plot, b0, p0, b1, p1, rgb, width=2.0, dashed=False):
# --- chart kinds -------------------------------------------------------------
# Each _draw_<kind> takes (cr, widget); the series is DEMO_SERIES
# Each _draw_<kind> takes (cr, widget); the series is _bars(widget)
# unless noted. Derived series (Heikin-Ashi, Renko, VWAP, OBV, ...)
# are rebuilt from the demo bars, like C set_series does.
@@ -490,21 +738,21 @@ def _line_chart_base(cr, widget, values, line_rgb=None):
def _draw_candlestick(cr, widget):
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return
_draw_candles(cr, widget, plot, DEMO_SERIES, i0, i1)
_draw_candles(cr, widget, plot, _bars(widget), i0, i1)
_draw_x_axis(cr, widget, plot)
_draw_title(cr, widget, plot, _fmt(DEMO_SERIES[-1][3]))
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
def _draw_hollow(cr, widget):
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return
_draw_candles(cr, widget, plot, DEMO_SERIES, i0, i1, hollow=True)
_draw_candles(cr, widget, plot, _bars(widget), i0, i1, hollow=True)
_draw_x_axis(cr, widget, plot)
_draw_title(cr, widget, plot, _fmt(DEMO_SERIES[-1][3]))
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
def _heikin_ashi(bars):
@@ -521,7 +769,7 @@ def _heikin_ashi(bars):
def _draw_heikin_ashi(cr, widget):
bars = _heikin_ashi(DEMO_SERIES)
bars = _heikin_ashi(_bars(widget))
plot, i0, i1 = _chart_base(cr, widget, bars)
if plot is None:
return
@@ -531,34 +779,34 @@ def _draw_heikin_ashi(cr, widget):
def _draw_ohlc(cr, widget):
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return
_draw_ohlc_bars(cr, widget, plot, DEMO_SERIES, i0, i1)
_draw_ohlc_bars(cr, widget, plot, _bars(widget), i0, i1)
_draw_x_axis(cr, widget, plot)
_draw_title(cr, widget, plot, _fmt(DEMO_SERIES[-1][3]))
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
def _draw_line(cr, widget):
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return
line = _color(widget, "line-color", LINE_RGB)
width = _prop_int(widget, "line-width", 2)
_draw_line_values(cr, plot, _closes(DEMO_SERIES), i0, i1, line,
_draw_line_values(cr, plot, _closes(_bars(widget)), i0, i1, line,
width)
_draw_x_axis(cr, widget, plot)
_draw_title(cr, widget, plot, _fmt(DEMO_SERIES[-1][3]))
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
def _draw_area(cr, widget):
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return
line = _color(widget, "line-color", LINE_RGB)
fill = _color(widget, "fill-color", (180 / 255, 210 / 255, 240 / 255))
width = _prop_int(widget, "line-width", 2)
closes = _closes(DEMO_SERIES)
closes = _closes(_bars(widget))
bottom = plot.py + plot.ph
cr.save()
_rgb(cr, fill, 0.55)
@@ -580,11 +828,11 @@ def _draw_area(cr, widget):
cr.restore()
_draw_line_values(cr, plot, closes, i0, i1, line, width)
_draw_x_axis(cr, widget, plot)
_draw_title(cr, widget, plot, _fmt(DEMO_SERIES[-1][3]))
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
def _draw_baseline(cr, widget):
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return
baseline = _prop_float(widget, "baseline", 100.0)
@@ -595,7 +843,7 @@ def _draw_baseline(cr, widget):
line = _color(widget, "line-color", LINE_RGB)
base_rgb = _color(widget, "baseline-color",
(120 / 255, 120 / 255, 120 / 255))
closes = _closes(DEMO_SERIES)
closes = _closes(_bars(widget))
base_y = plot.y(baseline)
bottom = plot.py + plot.ph
cr.save()
@@ -615,7 +863,7 @@ def _draw_baseline(cr, widget):
_draw_line_values(cr, plot, closes, i0, i1, line,
_prop_int(widget, "line-width", 2))
_draw_x_axis(cr, widget, plot)
_draw_title(cr, widget, plot, _fmt(DEMO_SERIES[-1][3]))
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
def _renko_bricks(bars, brick_size):
@@ -635,7 +883,7 @@ def _renko_bricks(bars, brick_size):
def _draw_renko(cr, widget):
brick_size = max(0.01, _prop_float(widget, "brick-size", 1.0))
bricks = _renko_bricks(DEMO_SERIES, brick_size)
bricks = _renko_bricks(_bars(widget), brick_size)
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
frame = _frame(widget)
if frame is None:
@@ -684,7 +932,7 @@ def _volume_values(bars):
def _draw_volume_bars(cr, widget):
volumes = _volume_values(DEMO_SERIES)
volumes = _volume_values(_bars(widget))
plot, i0, i1 = _line_chart_base(
cr, widget, volumes, line_rgb=None)
if plot is None:
@@ -700,7 +948,7 @@ def _draw_volume_bars(cr, widget):
h = volumes[i] / vmax * plot.ph
cx = plot.x(i)
cr.save()
_rgb(cr, up if DEMO_SERIES[i][3] >= DEMO_SERIES[i][0] else down)
_rgb(cr, up if _bars(widget)[i][3] >= _bars(widget)[i][0] else down)
cr.rectangle(cx - bw / 2, bottom - h, bw, h)
cr.fill()
cr.restore()
@@ -708,15 +956,15 @@ def _draw_volume_bars(cr, widget):
def _draw_volume_candles(cr, widget):
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return
# Candles on the top 2/3, volume bars on the bottom 1/3.
top_h = plot.ph * 2 / 3
sub = _Plot(widget, (plot.px, plot.py, plot.pw, top_h),
plot.lo, plot.hi, plot.first, plot.count, plot.total)
_draw_candles(cr, widget, sub, DEMO_SERIES, i0, i1)
volumes = _volume_values(DEMO_SERIES)
_draw_candles(cr, widget, sub, _bars(widget), i0, i1)
volumes = _volume_values(_bars(widget))
vmax = max(volumes[i0:i1], default=1.0) or 1.0
up = _color(widget, "up-color", UP_RGB)
down = _color(widget, "down-color", DOWN_RGB)
@@ -729,23 +977,23 @@ def _draw_volume_candles(cr, widget):
h = volumes[i] / vmax * vol_h
cx = plot.x(i)
cr.save()
_rgb(cr, up if DEMO_SERIES[i][3] >= DEMO_SERIES[i][0] else down)
_rgb(cr, up if _bars(widget)[i][3] >= _bars(widget)[i][0] else down)
cr.rectangle(cx - bw / 2, bottom - h, bw, h)
cr.fill()
cr.restore()
_draw_x_axis(cr, widget, plot)
_draw_title(cr, widget, plot, _fmt(DEMO_SERIES[-1][3]))
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
def _draw_volume_profile(cr, widget):
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return
_draw_candles(cr, widget, plot, DEMO_SERIES, i0, i1)
_draw_candles(cr, widget, plot, _bars(widget), i0, i1)
bins = max(2, _prop_int(widget, "bins", 20))
poc_rgb = _color(widget, "poc-color", DOWN_RGB)
line = _color(widget, "line-color", LINE_RGB)
vis = DEMO_SERIES[i0:i1]
vis = _bars(widget)[i0:i1]
if vis:
lo = min(b[2] for b in vis)
hi = max(b[1] for b in vis)
@@ -776,7 +1024,7 @@ def _draw_volume_profile(cr, widget):
cr.stroke()
cr.restore()
_draw_x_axis(cr, widget, plot)
_draw_title(cr, widget, plot, _fmt(DEMO_SERIES[-1][3]))
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
def _vwap_values(bars):
@@ -792,8 +1040,8 @@ def _vwap_values(bars):
def _draw_vwap(cr, widget):
values = _vwap_values(DEMO_SERIES)
closes = _closes(DEMO_SERIES)
values = _vwap_values(_bars(widget))
closes = _closes(_bars(widget))
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=None)
if plot is None:
return
@@ -821,7 +1069,7 @@ def _obv_values(bars):
def _draw_obv(cr, widget):
line = _color(widget, "line-color", LINE_RGB)
plot, i0, i1 = _line_chart_base(cr, widget, _obv_values(DEMO_SERIES),
plot, i0, i1 = _line_chart_base(cr, widget, _obv_values(_bars(widget)),
line_rgb=line)
if plot is None:
return
@@ -844,7 +1092,7 @@ def _accum_dist_values(bars):
def _draw_accum_dist(cr, widget):
line = _color(widget, "line-color", (0.0, 150 / 255, 0.0))
plot, i0, i1 = _line_chart_base(
cr, widget, _accum_dist_values(DEMO_SERIES), line_rgb=line)
cr, widget, _accum_dist_values(_bars(widget)), line_rgb=line)
if plot is None:
return
_draw_title(cr, widget, plot, "")
@@ -865,7 +1113,7 @@ def _money_flow_values(bars):
def _draw_money_flow(cr, widget):
values = _money_flow_values(DEMO_SERIES)
values = _money_flow_values(_bars(widget))
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=None)
if plot is None:
return
@@ -904,8 +1152,8 @@ def _rolling_corr(a, b, window):
def _draw_correlation(cr, widget):
window = max(2, _prop_int(widget, "window", 20))
values = _rolling_corr(_closes(DEMO_SERIES),
_closes(DEMO_SERIES_2), window)
values = _rolling_corr(_closes(_bars(widget)),
_closes(_bars(widget, 2)), window)
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=None)
if plot is None:
return
@@ -937,10 +1185,10 @@ def _indexed(bars, base_value=100.0):
def _draw_indexed(cr, widget):
base = _prop_float(widget, "base-value", 100.0)
first, count = _view(widget, len(DEMO_SERIES))
first, count = _view(widget, len(_bars(widget)))
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
series = [_indexed(DEMO_SERIES, base),
_indexed(DEMO_SERIES_2, base)]
series = [_indexed(_bars(widget), base),
_indexed(_bars(widget, 2), base)]
lo = min(min(s[i0:i1]) for s in series)
hi = max(max(s[i0:i1]) for s in series)
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
@@ -951,7 +1199,7 @@ def _draw_indexed(cr, widget):
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
return
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
len(DEMO_SERIES))
len(_bars(widget)))
_draw_grid(cr, widget, plot)
base_rgb = _color(widget, "base-line-color",
(180 / 255, 180 / 255, 180 / 255))
@@ -972,10 +1220,10 @@ def _draw_indexed(cr, widget):
def _draw_relative_perf(cr, widget):
first, count = _view(widget, len(DEMO_SERIES))
first, count = _view(widget, len(_bars(widget)))
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
series = []
for bars in (DEMO_SERIES, DEMO_SERIES_2, DEMO_SERIES_3):
for bars in (_bars(widget), _bars(widget, 2), _bars(widget, 3)):
base = bars[0][3]
series.append([(c - base) / base * 100.0
for c in _closes(bars)])
@@ -989,7 +1237,7 @@ def _draw_relative_perf(cr, widget):
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
return
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
len(DEMO_SERIES))
len(_bars(widget)))
_draw_grid(cr, widget, plot)
zero = _color(widget, "zero-line-color",
(180 / 255, 180 / 255, 180 / 255))
@@ -1010,7 +1258,7 @@ def _draw_relative_perf(cr, widget):
def _draw_ratio(cr, widget):
a, b = _closes(DEMO_SERIES), _closes(DEMO_SERIES_2)
a, b = _closes(_bars(widget)), _closes(_bars(widget, 2))
values = [x / y if y else 0.0 for x, y in zip(a, b)]
line = _color(widget, "line-color", (120 / 255, 60 / 255, 180 / 255))
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=line)
@@ -1020,7 +1268,7 @@ def _draw_ratio(cr, widget):
def _draw_spread(cr, widget):
a, b = _closes(DEMO_SERIES), _closes(DEMO_SERIES_2)
a, b = _closes(_bars(widget)), _closes(_bars(widget, 2))
values = [x - y for x, y in zip(a, b)]
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=None)
if plot is None:
@@ -1048,9 +1296,9 @@ def _draw_sector(cr, widget):
for label in labels:
if label not in seen:
seen.append(label)
series = [_indexed(DEMO_SERIES), _indexed(DEMO_SERIES_2),
_indexed(DEMO_SERIES_3)]
first, count = _view(widget, len(DEMO_SERIES))
series = [_indexed(_bars(widget)), _indexed(_bars(widget, 2)),
_indexed(_bars(widget, 3))]
first, count = _view(widget, len(_bars(widget)))
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
lo = min(min(s[i0:i1]) for s in series)
hi = max(max(s[i0:i1]) for s in series)
@@ -1062,7 +1310,7 @@ def _draw_sector(cr, widget):
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
return
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
len(DEMO_SERIES))
len(_bars(widget)))
_draw_grid(cr, widget, plot)
colours = (LINE_RGB, DOWN_RGB, (0.0, 150 / 255, 0.0))
for values, rgb in zip(series, colours):
@@ -1082,9 +1330,9 @@ def _draw_sector(cr, widget):
def _draw_multi_symbol(cr, widget):
series = [_indexed(DEMO_SERIES), _indexed(DEMO_SERIES_2),
_indexed(DEMO_SERIES_3)]
first, count = _view(widget, len(DEMO_SERIES))
series = [_indexed(_bars(widget)), _indexed(_bars(widget, 2)),
_indexed(_bars(widget, 3))]
first, count = _view(widget, len(_bars(widget)))
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
lo = min(min(s[i0:i1]) for s in series)
hi = max(max(s[i0:i1]) for s in series)
@@ -1096,7 +1344,7 @@ def _draw_multi_symbol(cr, widget):
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
return
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
len(DEMO_SERIES))
len(_bars(widget)))
_draw_grid(cr, widget, plot)
for values, rgb in zip(series, (LINE_RGB, DOWN_RGB,
(0.0, 150 / 255, 0.0))):
@@ -1106,10 +1354,10 @@ def _draw_multi_symbol(cr, widget):
def _draw_overlay(cr, widget):
first, count = _view(widget, len(DEMO_SERIES))
first, count = _view(widget, len(_bars(widget)))
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
main = _closes(DEMO_SERIES)
other = _closes(DEMO_SERIES_2)
main = _closes(_bars(widget))
other = _closes(_bars(widget, 2))
lo = min(min(main[i0:i1]), min(other[i0:i1]))
hi = max(max(main[i0:i1]), max(other[i0:i1]))
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
@@ -1120,7 +1368,7 @@ def _draw_overlay(cr, widget):
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
return
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
len(DEMO_SERIES))
len(_bars(widget)))
_draw_grid(cr, widget, plot)
_draw_line_values(cr, plot, main, i0, i1, LINE_RGB, 2.0)
cr.save()
@@ -1146,8 +1394,10 @@ def _draw_overlay(cr, widget):
def _draw_price(cr, widget):
"""Price label: big last close + day change (kind "Price")."""
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
last = DEMO_SERIES[-1][3]
prev = DEMO_SERIES[-2][3]
bars = _bars(widget)
last = bars[-1][3]
# A one-bar series has no previous close: show a flat change.
prev = bars[-2][3] if len(bars) >= 2 else last
change = last - prev
rgb = UP_RGB if change >= 0 else DOWN_RGB
sign = "+" if change >= 0 else ""
@@ -1168,10 +1418,10 @@ def _draw_price(cr, widget):
def _tool_base(cr, widget):
"""Candle background + plot for a tool; (plot, i0, i1)."""
plot, i0, i1 = _chart_base(cr, widget, DEMO_SERIES)
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
if plot is None:
return None, 0, 0
_draw_candles(cr, widget, plot, DEMO_SERIES, i0, i1)
_draw_candles(cr, widget, plot, _bars(widget), i0, i1)
return plot, i0, i1
@@ -1202,7 +1452,7 @@ def _draw_trendline(cr, widget):
cr.restore()
else:
_line_through(cr, plot, 0, plot.lo + (plot.hi - plot.lo) * 0.25,
len(DEMO_SERIES) - 1,
len(_bars(widget)) - 1,
plot.lo + (plot.hi - plot.lo) * 0.75, colour, width)
_tool_finish(cr, widget, plot, anchors)
@@ -1233,7 +1483,7 @@ def _draw_vertical_line(cr, widget):
anchors = _anchors(widget)
colour = _color(widget, "color", (120 / 255, 60 / 255, 180 / 255))
width = _prop_int(widget, "line-width", 2)
bar = anchors[0][0] if anchors else len(DEMO_SERIES) // 2
bar = anchors[0][0] if anchors else len(_bars(widget)) // 2
cr.save()
_rgb(cr, colour)
cr.set_line_width(width)
@@ -1589,13 +1839,130 @@ _CHART_DRAW = {
}
def _no_data(cr, widget):
"""Border + 'no data' placeholder for a widget whose series was
cleared (see StockWidget._draw)."""
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
_wtext(cr, widget, widget.pkind, widget.width / 2,
widget.height / 2 - 4, size=12, align="center",
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
_wtext(cr, widget, "No data -- call set_series() or load_csv()",
widget.width / 2, widget.height / 2 + 14, size=11,
align="center", rgb=(0.4, 0.4, 0.4),
max_width=widget.width - 12)
class StockWidget(Widget):
"""One of the 37 Stock Market widgets (archetype Chart/Label in
the palette, drawn here instead of the generic panel)."""
ARCHETYPE = "Chart"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Own series per slot (1, 2, 3): None means "use the built-in
# demo series for that slot"; a list (possibly empty) is data
# the user fed in. Runtime state only -- never saved in .fdj.
self._series = [None, None, None]
# --- data ingestion (set_series is the C API; load_csv is new) -----
def set_series(self, bars, which=1):
"""Replace the series in slot *which* (1, 2 or 3).
*bars* is a list of (open, high, low, close, volume) tuples
(or dicts with those keys), or None to revert the slot to the
built-in demo series. Resets the view window (like C
``set_series``) and marks the widget dirty so the host
redraws. The multi-symbol charts read slots 2/3 as their
second/third symbols.
"""
if not 1 <= which <= 3:
raise ValueError("series slot must be 1, 2 or 3, got %r"
% (which,))
self._series[which - 1] = _validate_bars(bars)
if "view-first" in self.prop_names():
self.props.pop("view-first", None)
if "view-count" in self.prop_names():
self.props.pop("view-count", None)
self._mark_dirty()
def populate(self, bars, which=1):
"""Alias for ``set_series``: fill the widget with *bars*.
The clear/populate pair: ``widget.clear()`` empties the
series, ``widget.populate(bars)`` (or ``set_series``) refills
it.
"""
self.set_series(bars, which=which)
def get_series(self, which=1):
"""The bars slot *which* currently plots: the widget's own
series when set, else the built-in demo series for that slot.
Returns a copy, so callers cannot mutate the plotted data.
"""
return list(_bars(self, which))
def add_point(self, bar):
"""Append one (open, high, low, close, volume) bar to the
primary series and return the new bar count.
If no own series was set yet, this starts a fresh series
(it does NOT extend the demo series)."""
bar = _validate_bars([bar], what="add_point")[0]
if self._series[0] is None:
self._series[0] = []
self._series[0].append(bar)
self._mark_dirty()
return len(self._series[0])
def clear(self, which=0):
"""Empty the series: *which* 0 clears all three slots, 1..3
clears one slot. A cleared widget draws the no-data
placeholder until ``populate`` / ``set_series`` refills it
(or ``set_series(None)`` restores the demo series).
"""
if which == 0:
self._series = [[], [], []]
elif 1 <= which <= 3:
self._series[which - 1] = []
else:
raise ValueError("series slot must be 0..3, got %r"
% (which,))
self._mark_dirty()
def load_csv(self, source, which=1):
"""Load OHLCV bars from a CSV file into slot *which*.
*source* is a path or a file-like object; see module
``load_csv`` for the format. Returns the number of bars
loaded. Raises ValueError naming the offending row on bad
data, and leaves the previous series untouched in that case.
"""
bars = load_csv(source)
self.set_series(bars, which=which)
return len(bars)
def item_count(self, which=1):
"""Number of bars slot *which* currently plots (C parity)."""
return len(_bars(self, which))
def _draw(self, cr):
# A cleared series draws the no-data placeholder instead of a
# chart: every _draw_<kind> indexes bars[-1]/bars[0], so the
# check has to happen before dispatch, not inside each kind.
# Multi-symbol kinds need their extra slots too.
own = self._series
if own[0] is not None and len(own[0]) == 0:
_no_data(cr, self)
return
if self.pkind in _MULTI_KINDS:
if own[1] is not None and len(own[1]) == 0:
_no_data(cr, self)
return
if (self.pkind in _THREE_SERIES_KINDS
and own[2] is not None and len(own[2]) == 0):
_no_data(cr, self)
return
draw = _CHART_DRAW.get(self.pkind)
if draw is not None:
draw(cr, self)
+31
View File
@@ -0,0 +1,31 @@
date,open,high,low,close,volume
2026-01-05,100.00,100.18,98.80,99.40,530827
2026-01-06,99.40,99.94,99.30,99.58,1196376
2026-01-07,99.58,100.00,97.81,97.92,558790
2026-01-08,97.92,98.67,97.53,97.69,761555
2026-01-09,97.69,99.07,97.15,98.21,1026921
2026-01-12,98.21,100.11,97.43,100.02,863102
2026-01-13,100.02,100.17,98.44,98.75,1668673
2026-01-14,98.75,99.29,97.03,97.62,989768
2026-01-15,97.62,97.95,97.52,97.85,735116
2026-01-16,97.85,98.98,97.53,98.57,1315909
2026-01-19,98.57,98.87,97.72,98.45,1489461
2026-01-20,98.45,98.99,97.05,97.55,1758960
2026-01-21,97.55,98.74,96.67,98.45,600640
2026-01-22,98.45,99.14,98.02,98.20,1168113
2026-01-23,98.20,98.82,95.85,96.55,1296729
2026-01-26,96.55,98.31,95.91,97.99,1329385
2026-01-27,97.99,98.78,97.23,98.34,1865362
2026-01-28,98.34,98.95,98.19,98.29,1493282
2026-01-29,98.29,99.77,97.54,98.88,855431
2026-01-30,98.88,99.50,98.44,98.51,1126393
2026-02-02,98.51,98.66,97.23,97.33,1595396
2026-02-03,97.33,97.59,95.63,96.01,1753275
2026-02-04,96.01,96.44,93.99,94.51,1771577
2026-02-05,94.51,96.52,94.22,95.74,1055403
2026-02-06,95.74,96.54,94.41,95.27,650908
2026-02-09,95.27,95.52,93.87,94.12,1161992
2026-02-10,94.12,94.77,94.07,94.50,1060988
2026-02-11,94.50,95.03,93.21,94.07,1476455
2026-02-12,94.07,94.75,93.45,94.18,502609
2026-02-13,94.18,96.42,93.39,95.71,1640745
1 date open high low close volume
2 2026-01-05 100.00 100.18 98.80 99.40 530827
3 2026-01-06 99.40 99.94 99.30 99.58 1196376
4 2026-01-07 99.58 100.00 97.81 97.92 558790
5 2026-01-08 97.92 98.67 97.53 97.69 761555
6 2026-01-09 97.69 99.07 97.15 98.21 1026921
7 2026-01-12 98.21 100.11 97.43 100.02 863102
8 2026-01-13 100.02 100.17 98.44 98.75 1668673
9 2026-01-14 98.75 99.29 97.03 97.62 989768
10 2026-01-15 97.62 97.95 97.52 97.85 735116
11 2026-01-16 97.85 98.98 97.53 98.57 1315909
12 2026-01-19 98.57 98.87 97.72 98.45 1489461
13 2026-01-20 98.45 98.99 97.05 97.55 1758960
14 2026-01-21 97.55 98.74 96.67 98.45 600640
15 2026-01-22 98.45 99.14 98.02 98.20 1168113
16 2026-01-23 98.20 98.82 95.85 96.55 1296729
17 2026-01-26 96.55 98.31 95.91 97.99 1329385
18 2026-01-27 97.99 98.78 97.23 98.34 1865362
19 2026-01-28 98.34 98.95 98.19 98.29 1493282
20 2026-01-29 98.29 99.77 97.54 98.88 855431
21 2026-01-30 98.88 99.50 98.44 98.51 1126393
22 2026-02-02 98.51 98.66 97.23 97.33 1595396
23 2026-02-03 97.33 97.59 95.63 96.01 1753275
24 2026-02-04 96.01 96.44 93.99 94.51 1771577
25 2026-02-05 94.51 96.52 94.22 95.74 1055403
26 2026-02-06 95.74 96.54 94.41 95.27 650908
27 2026-02-09 95.27 95.52 93.87 94.12 1161992
28 2026-02-10 94.12 94.77 94.07 94.50 1060988
29 2026-02-11 94.50 95.03 93.21 94.07 1476455
30 2026-02-12 94.07 94.75 93.45 94.18 502609
31 2026-02-13 94.18 96.42 93.39 95.71 1640745
+327
View File
@@ -0,0 +1,327 @@
"""Stock chart data ingestion: CSV loading + set_series/clear/populate.
- ``load_csv`` (module function + ``StockWidget.load_csv``): the
tests/data/ohlcv_30.csv fixture (30 real weekday bars), header /
no-header / shuffled-columns / date formats, and every ValueError
path naming the offending row.
- Series API: set/get round-trip, ``set_series(None)`` restores the
demo series, ``add_point`` starts a fresh series, ``clear`` /
``populate``, ``item_count``, view reset on ``set_series``.
- Rendering: every in-scope chart kind (the 24 that plot a data
series) draws CSV data headless without raising, the CSV render
differs from the template render (proving the CSV data is what is
plotted), a one-bar series draws, and a cleared series draws the
no-data placeholder.
"""
import io
import os
import unittest
import cairo
from lightgui.xframe import core
from lightgui.xframe import stock as stock_mod
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CSV_PATH = os.path.join(REPO, "tests", "data", "ohlcv_30.csv")
# The 13 Stock kinds that are pure drawing tools (anchors, no data
# input) -- everything else in STOCK_KINDS plots a data series.
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)
CHART_NAMES = {"Stock" + k if k != "Price" else "StockPriceLabel"
for k in CHART_KINDS}
def _make(name, width=400, height=300):
widget = core.create(name, name + "_001", 0, 0, width, height)
assert widget is not None, name
return widget
def _draw(widget):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
widget.width + 4, widget.height + 4)
cr = cairo.Context(surface)
cr.set_source_rgb(1, 1, 1)
cr.paint()
widget.draw(cr)
return surface
def _png_bytes(surface):
buf = io.BytesIO()
surface.write_to_png(buf)
return buf.getvalue()
def _non_white_pixels(surface):
data = surface.get_data()
stride = surface.get_stride()
count = 0
for y in range(surface.get_height()):
row = data[y * stride:(y + 1) * stride]
for x in range(0, len(row), 4):
b, g, r = row[x], row[x + 1], row[x + 2]
if (r, g, b) != (255, 255, 255):
count += 1
return count
def _csv_text(rows, header="date,open,high,low,close,volume"):
lines = [header] if header is not None else []
lines += [",".join(str(c) for c in row) for row in rows]
return "\n".join(lines) + "\n"
GOOD_ROWS = [
("2026-03-02", 50.0, 51.0, 49.5, 50.5, 100000),
("2026-03-03", 50.5, 52.0, 50.0, 51.5, 120000),
("2026-03-04", 51.5, 51.8, 50.8, 51.0, 90000),
]
class LoadCsvTests(unittest.TestCase):
def test_fixture_loads_30_rows(self):
bars = stock_mod.load_csv(CSV_PATH)
self.assertEqual(len(bars), 30)
self.assertEqual(bars[0], (100.0, 100.18, 98.8, 99.4, 530827.0))
self.assertEqual(bars[-1][3], 95.71)
for open_v, high, low, close, volume in bars:
self.assertGreaterEqual(high, max(open_v, close))
self.assertLessEqual(low, min(open_v, close))
self.assertGreater(volume, 0)
def test_no_header(self):
text = _csv_text(GOOD_ROWS, header=None)
bars = stock_mod.load_csv(io.StringIO(text))
self.assertEqual(bars, [tuple(map(float, r[1:]))
for r in GOOD_ROWS])
def test_columns_matched_by_name_shuffled_plus_extra(self):
rows = [(r[0], r[5], r[4], r[3], r[2], r[1], 51.25)
for r in GOOD_ROWS]
text = _csv_text(
rows, header="date,volume,close,low,high,open,adj close")
bars = stock_mod.load_csv(io.StringIO(text))
self.assertEqual(bars, [tuple(map(float, r[1:]))
for r in GOOD_ROWS])
def test_aliases_and_date_formats(self):
rows = [
("2026/03/02", 50.0, 51.0, 49.5, 50.5, 100000),
("02-03-2026", 50.5, 52.0, 50.0, 51.5, 120000),
("2026-03-04 09:30:00", 51.5, 51.8, 50.8, 51.0, 90000),
("1772323200", 51.0, 51.5, 50.5, 51.2, 110000),
]
text = _csv_text(rows, header="timestamp,o,h,l,c,vol")
bars = stock_mod.load_csv(io.StringIO(text))
self.assertEqual(len(bars), 4)
self.assertEqual(bars[0], (50.0, 51.0, 49.5, 50.5, 100000.0))
def test_bad_float_names_row(self):
text = _csv_text([("2026-03-02", 50.0, "xx", 49.5, 50.5, 100)])
with self.assertRaises(ValueError) as ctx:
stock_mod.load_csv(io.StringIO(text))
self.assertIn("row 2", str(ctx.exception))
self.assertIn("high", str(ctx.exception))
def test_bad_date_names_row(self):
text = _csv_text([("not-a-date", 50.0, 51.0, 49.5, 50.5, 100)])
with self.assertRaises(ValueError) as ctx:
stock_mod.load_csv(io.StringIO(text))
self.assertIn("row 2", str(ctx.exception))
def test_high_below_close_suggests_column_order(self):
text = _csv_text([("2026-03-02", 51.0, 50.0, 49.5, 50.5, 100)])
with self.assertRaises(ValueError) as ctx:
stock_mod.load_csv(io.StringIO(text))
self.assertIn("column order", str(ctx.exception))
def test_negative_volume(self):
text = _csv_text([("2026-03-02", 50.0, 51.0, 49.5, 50.5, -5)])
with self.assertRaises(ValueError):
stock_mod.load_csv(io.StringIO(text))
def test_short_row_and_wrong_column_count(self):
text = _csv_text([("2026-03-02", 50.0, 51.0, 49.5, 50.5)])
with self.assertRaises(ValueError) as ctx:
stock_mod.load_csv(io.StringIO(text))
self.assertIn("row 2", str(ctx.exception))
def test_partial_header_names_missing_column(self):
text = "date,open,high,low,close\n2026-03-02,50,51,49.5,50.5\n"
with self.assertRaises(ValueError) as ctx:
stock_mod.load_csv(io.StringIO(text))
self.assertIn("volume", str(ctx.exception))
def test_empty_and_header_only_raise(self):
with self.assertRaises(ValueError):
stock_mod.load_csv(io.StringIO(""))
with self.assertRaises(ValueError):
stock_mod.load_csv(io.StringIO("date,open,high,low,close,volume\n"))
def test_missing_file_raises(self):
with self.assertRaises(OSError):
stock_mod.load_csv(os.path.join(REPO, "tests", "data",
"no-such-file.csv"))
class SeriesApiTests(unittest.TestCase):
def test_set_get_round_trip_and_copy(self):
widget = _make("StockLineChart")
bars = stock_mod.load_csv(CSV_PATH)
widget.set_series(bars)
self.assertEqual(widget.get_series(), bars)
got = widget.get_series()
got.append((1.0, 2.0, 0.5, 1.5, 10.0))
self.assertEqual(widget.item_count(), 30) # copy, not alias
def test_set_series_none_restores_demo(self):
widget = _make("StockLineChart")
widget.set_series(stock_mod.load_csv(CSV_PATH))
self.assertEqual(widget.item_count(), 30)
widget.set_series(None)
self.assertEqual(widget.get_series(), stock_mod.DEMO_SERIES)
self.assertEqual(widget.item_count(), 250)
def test_set_series_dict_bars_and_validation(self):
widget = _make("StockLineChart")
widget.set_series([{"open": 1.0, "high": 2.0, "low": 0.5,
"close": 1.5, "volume": 10.0}])
self.assertEqual(widget.get_series(),
[(1.0, 2.0, 0.5, 1.5, 10.0)])
with self.assertRaises(ValueError):
widget.set_series([(1.0, 2.0)]) # too short
with self.assertRaises(ValueError):
widget.set_series([(1.0, 0.5, 2.0, 1.5, 10.0)]) # high < low
def test_set_series_bad_slot(self):
widget = _make("StockLineChart")
with self.assertRaises(ValueError):
widget.set_series([], which=4)
def test_add_point_starts_fresh(self):
widget = _make("StockLineChart")
self.assertEqual(widget.item_count(), 250) # demo until fed
n = widget.add_point((10.0, 11.0, 9.5, 10.5, 1000.0))
self.assertEqual(n, 1)
self.assertEqual(widget.item_count(), 1)
self.assertEqual(widget.get_series(),
[(10.0, 11.0, 9.5, 10.5, 1000.0)])
with self.assertRaises(ValueError):
widget.add_point((1.0, 2.0)) # malformed bar
def test_clear_populate_workflow(self):
widget = _make("StockCandlestickChart")
widget.load_csv(CSV_PATH)
self.assertEqual(widget.item_count(), 30)
widget.clear()
self.assertEqual(widget.item_count(), 0)
self.assertEqual(widget.get_series(), [])
widget.populate(stock_mod.load_csv(CSV_PATH))
self.assertEqual(widget.item_count(), 30)
def test_clear_one_slot_only(self):
widget = _make("StockOverlayChart")
widget.set_series(stock_mod.load_csv(CSV_PATH), which=2)
self.assertEqual(widget.item_count(2), 30)
self.assertEqual(widget.item_count(1), 250) # demo untouched
widget.clear(which=2)
self.assertEqual(widget.item_count(2), 0)
self.assertEqual(widget.item_count(1), 250)
with self.assertRaises(ValueError):
widget.clear(which=5)
def test_load_csv_method_returns_count_and_keeps_old_on_error(self):
widget = _make("StockLineChart")
self.assertEqual(widget.load_csv(CSV_PATH), 30)
bad = io.StringIO("date,open,high,low,close,volume\n"
"2026-03-02,50,bad,49.5,50.5,100\n")
with self.assertRaises(ValueError):
widget.load_csv(bad)
self.assertEqual(widget.item_count(), 30) # untouched
def test_view_resets_on_set_series(self):
widget = _make("StockCandlestickChart")
widget.set_prop("view-first", "10")
widget.set_prop("view-count", "50")
widget.set_series(stock_mod.load_csv(CSV_PATH))
self.assertEqual(widget.get_prop("view-first", ""), "")
self.assertEqual(widget.get_prop("view-count", ""), "")
def test_demo_series_never_mutated(self):
first = stock_mod.DEMO_SERIES[0]
widget = _make("StockCandlestickChart")
widget.load_csv(CSV_PATH)
_draw(widget)
self.assertEqual(stock_mod.DEMO_SERIES[0], first)
self.assertEqual(len(stock_mod.DEMO_SERIES), 250)
class CsvRenderTests(unittest.TestCase):
def test_all_chart_kinds_draw_csv_data(self):
bars = stock_mod.load_csv(CSV_PATH)
for name in sorted(CHART_NAMES):
widget = _make(name)
widget.load_csv(CSV_PATH)
surface = _draw(widget) # must not raise
self.assertGreater(_non_white_pixels(surface), 100,
"%s drew nothing with CSV data" % name)
# Multi-symbol kinds also plot their extra slots.
if name in ("StockCorrelationView", "StockIndexedComparison",
"StockMultiSymbolChart", "StockOverlayChart",
"StockRatioChart", "StockRelativePerformance",
"StockSectorComparison", "StockSpreadChart"):
widget.set_series(bars, which=2)
if name in ("StockMultiSymbolChart",
"StockRelativePerformance",
"StockSectorComparison"):
widget.set_series(bars, which=3)
surface = _draw(widget)
self.assertGreater(_non_white_pixels(surface), 100, name)
def test_csv_render_differs_from_template(self):
# The CSV data must be what is plotted: same widget, same
# size, template render vs CSV render must differ a lot.
for name in ("StockCandlestickChart", "StockLineChart",
"StockVolumeBars", "StockVWAP", "StockPriceLabel"):
template = _draw(_make(name))
csv_widget = _make(name)
csv_widget.load_csv(CSV_PATH)
csv_render = _draw(csv_widget)
self.assertNotEqual(_png_bytes(template),
_png_bytes(csv_render), name)
self.assertGreater(_non_white_pixels(template), 100, name)
self.assertGreater(_non_white_pixels(csv_render), 100, name)
def test_one_bar_series_draws_every_chart_kind(self):
for name in sorted(CHART_NAMES):
widget = _make(name)
widget.set_series([(100.0, 101.0, 99.0, 100.5, 500000.0)])
_draw(widget) # must not raise (Price: no previous close)
def test_cleared_series_draws_placeholder(self):
for name in sorted(CHART_NAMES):
widget = _make(name)
widget.load_csv(CSV_PATH)
widget.clear()
surface = _draw(widget) # must not raise
self.assertGreater(_non_white_pixels(surface), 50,
"%s drew nothing when cleared" % name)
def test_tool_kinds_inherit_loaded_series_as_background(self):
# Drawing tools take no data input, but they draw over the
# candle chart, so a loaded series changes their background.
template = _draw(_make("StockTrendline"))
tool = _make("StockTrendline")
tool.load_csv(CSV_PATH)
self.assertNotEqual(_png_bytes(template), _png_bytes(_draw(tool)))
if __name__ == "__main__":
unittest.main()
+234
View File
@@ -0,0 +1,234 @@
#!/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())