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).
250 lines
9.7 KiB
Markdown
250 lines
9.7 KiB
Markdown
# 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/`.
|