Ind* indicators: CSV/series support on all 250 kinds

Transpile the C component ind_* function for every kind into
lightgui/xframe/indicators.py (tools/transpile_indicators.py), verified
250/250 against the C++ reference dump (<=1e-9, NaN patterns included).
IndicatorWidget gains the StockWidget series API (set_series, populate,
get_series, add_point, clear, load_csv, item_count, get_lines) and draws
the computed lines (14-colour palette, NaN gaps, dots for isolated
marker points) with the demo series as fallback. Docs in
docs/indicators-data.md; tests/test_indicators_csv.py (17 tests, golden
spot values vs the C++ reference); Xvfb shots via
tools/ind_csv_shots.py.
This commit is contained in:
cnmcdee committed 2026-12-02 11:04:35 +00:00
1 parent d0f430f88c
commit 3b67cbf9de
6 files changed
+7447 -1

No files matched your search

+219
View File
@@ -0,0 +1,219 @@
# Ind* indicator widgets: plotting your own data
The 250 Ind* indicators -- RSI, MACD, Bollinger Bands, ADX, Guppy
MMA, the whole palette -- all draw from the same data model as the
Stock chart widgets, and all take real data the same way:
`set_series()` for bars you already hold in Python, or `load_csv()`
for an OHLCV file. Each kind recomputes its own lines from the loaded
bars; nothing is hard-coded to the demo series any more.
This is the companion to `stock-charts-data.md`: same bar model, same
CSV spec, same series API (single slot -- indicators have no
second/third symbol). Read that doc for the CSV format details; this
doc covers what is different about indicators.
## 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.
## Template data: what ships inside each widget
With no data fed in, every indicator 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.
## How the lines are computed
`lightgui/xframe/indicators.py` is generated, not hand-written: the
transpiler in `tools/transpile_indicators.py` translates the C
component `ind_*` function for each kind
(`widgets/components/Ind*/Ind*.h` in the C repo) into Python, one
function per kind, plus the shared helpers they call. The generated
module carries a `INDICATOR_INFO` registry per kind: which function
to call, whether it takes whole bars or closes, its default
parameters, and which of its outputs are plotted lines.
The transpiled code is numerically verified against the C++ reference:
all 250 kinds, on the seeded demo series, agree with the C++
component dump to within 1e-9 relative, including the NaN warm-up
patterns (see "Tests and screenshots" below). The Python port follows
the per-component `ind_*` functions, not the separate StockChart
overlay registry in the C repo -- the two disagree systematically
(different warm-up and seeding), and the components are the ones the
widgets actually plot.
Most kinds plot one line. The multi-line kinds plot all of theirs:
| Kinds | Lines |
| --- | --- |
| MACD, Bollinger Bands, Keltner Channels, Donchian Channels, and other band/channel kinds | 2-3 (e.g. macd/signal/histogram, upper/middle/lower) |
| Guppy MMA | 12 (six fast + six slow EMAs) |
| Moving Average Ribbon | 6 |
| Klinger Volume Oscillator | 2 (KVO + signal) |
Line colours cycle through the 14-colour palette from the Rust
`xframe-indicators` `plot.rs` `PLOT_PALETTE` (blue, orange, purple,
teal, magenta, brown, green, red, steel blue, olive, grey, gold,
indigo, brick). Lines are polylines with gaps where the indicator has
no value yet (NaN warm-up). Pattern/marker kinds whose values are
isolated single-bar pivots (FractalUp/Down, ZigZag) draw those points
as filled dots -- a polyline alone would leave no mark.
## API
All of this lives on `IndicatorWidget` (`lightgui/xframe/core.py`),
mirroring the `StockWidget` API with a single series slot:
```python
widget.set_series(bars) # replace the series
widget.get_series() # bars currently plotted (a copy)
widget.populate(bars) # alias for set_series
widget.clear() # empty the series
widget.add_point(bar) # append one bar, return new count
widget.load_csv(path) # load an OHLCV CSV, return bar count
widget.item_count() # number of bars plotted
widget.get_lines(params=None) # plotted lines for the current series
```
- `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` (same validation as the chart
widgets: wrong length, non-numeric, `high` below open/close, `low`
above open/close, negative volume).
- `set_series(None)` reverts to the built-in demo series.
- `clear()` empties the series; the widget then draws a "No data --
call set_series() or load_csv()" placeholder instead of lines until
`populate()` / `set_series()` refills it (or `set_series(None)`
restores the demo).
- `add_point()` appends to the series. If no own series was set yet
it starts a fresh series -- it does NOT extend the demo series.
- `get_lines()` returns the plotted lines for the current series: a
list of float lists, one value per bar, NaN where the indicator has
no value yet, in plot order. `params` overrides the kind's default
parameters positionally (e.g. `get_lines([7])` for RSI(7)).
Returns `[]` when the series was cleared. This is the same
computation the widget draws; use it in tests or in a generated
program that needs the numbers, not just the picture.
- Series data is runtime state only: it is NOT saved in `.fdj`
files, and it has no Inspector row. A project reloaded in the
designer shows the demo series again until the generated program
loads its data.
The compute functions are also usable directly, without a widget:
```python
from lightgui.xframe import indicators
from lightgui.xframe.stock import demo_series, load_csv
bars = load_csv("prices.csv")
lines = indicators.compute_lines("IndRSI", bars) # [rsi]
macd = indicators.compute_lines("IndMACD", bars) # [macd, signal, hist]
indicators.indicator_names() # all 250 kinds, in palette order
```
`compute_lines(kind, bars, params=None)` takes OHLCV bars (or, for
the closes-only kinds, it extracts closes internally). The default
parameters are the ones the C smoke tests use for that kind.
## CSV format
Identical to the chart widgets: `load_csv(source)` in
`lightgui/xframe/stock.py`, `source` a path or a file-like object,
`date,open,high,low,close,volume` with an optional header matched by
name (aliases `timestamp`/`time`/`datetime`, `o`/`h`/`l`/`c`,
`vol`/`v`). See `stock-charts-data.md` for the full spec and
validation rules. 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 RSI indicator, CSV data. Run it
from the repo root:
```python
#!/usr/bin/env python3
"""Plot an OHLCV CSV file in an IndRSI indicator."""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lightgui.xframe import core # noqa: E402
widget = core.create("IndRSI", "rsi_001", 0, 0, 400, 300)
widget.load_csv("tests/data/ohlcv_30.csv")
print("bars:", widget.item_count())
print("rsi[29]:", widget.get_lines()[0][29])
# ... hand widget to a window/canvas as usual; it draws the RSI line
# for the loaded bars. Without load_csv it would draw the RSI of the
# built-in demo series instead.
```
Every committed example in `examples/ind*.py` draws its kind on the
demo series; adding one `widget.load_csv(...)` line after the
`create(...)` call (as `tools/ind_csv_shots.py` does) switches it to
file data.
## Clear / populate workflow
```python
widget.clear() # placeholder: "No data -- ..."
widget.populate(bars) # back to lines
widget.set_series(None) # back to the demo series
```
## Limits
- **Warm-up:** most indicators need some bars before their first
finite value (RSI(14) from bar 14, Bollinger from bar 20, ADX from
bar 26). On a short file the lines start with NaNs -- that is the
indicator, not missing data. 36 of the 250 kinds need more than 30
bars for any finite value at all (multi-stage smoothing such as
TEMA/TRIX/KST, 52-bar Senkou Span B, Klinger slow EMA 55, Guppy
long leg 60); feed them a longer file.
- **Parameters:** the defaults are the C smoke-test parameters for
each kind. `get_lines(params)` overrides them positionally, but
there is no per-kind parameter editor on the widget yet -- the
values are not Inspector props.
- **One series per indicator:** unlike the multi-symbol charts, an
indicator has a single series slot; there is no second/third
symbol.
- **Series is runtime state only** (see API above): not saved in
`.fdj`, no Inspector row.
## Tests and screenshots
- `tests/test_indicators_csv.py` (17 tests): the series API
(set/get round-trip, `set_series(None)` restores the demo,
`add_point`, `clear`/`populate`, `item_count`, `load_csv` and its
error paths), golden spot values against the C++ reference (RSI,
MACD, Bollinger, SMA, EMA, ATR), a parameter override, load +
recompute for all 250 kinds on the demo series and the 30-bar CSV,
and rendering -- every kind draws demo and CSV data headless, the
CSV render differs from the demo render, a one-bar series draws,
and a cleared series draws the placeholder.
- `tools/transpile_indicators.py` -- the transpiler that generates
`lightgui/xframe/indicators.py` from the C repo. Its verification
pass (compare every kind's `compute_lines` output against the C++
component dump on the seeded demo series) must read **250 / 250
kinds match** before the generated module is committed.
- `tools/ind_csv_shots.py` -- Xvfb screenshots of all 250 kinds with
the 30-bar CSV loaded, each compared (ImageMagick RMSE) against its
template-data golden in `tools/visreg/goldens/`. A large RMSE means
the CSV data is what is plotted. Run from the repo root:
`python3 tools/ind_csv_shots.py`.