Files
lightgui/docs/stock-market-csv-data.md
T
cnmcdee 90880928c9 Ind* CSV series API: load_csv/set_series/clear_series on all 250 indicators
Every Ind* widget recomputes its lines from a loaded OHLCV series:
private recompute_lines() (moved out of the constructor), public
set_series()/load_csv()/clear_series()/series() matching the Stock*
chart widgets, same loader and CSV spec (StockData.h). Constructor
defaults keep the seeded 250-bar template; failed loads leave the
series untouched; clear_series() empties lines and draws clean.
Params that were constructor-only (fast/slow/period/...) are now
stored as members so a reloaded series uses the same settings.

Tests: widgets/tests/ind_csv_harness.cpp + test_ind_csv.py — 250/250
harnesses build, 250/250 numeric PASS, 39/39 screenshots PASS, 250/250
demo mains build. Docs: docs/stock-market-csv-data.md Indicators
section rewritten; all 250 cdoc pages updated (update-ind-csv.py).
2026-12-02 11:00:19 +00:00

15 KiB

Stock Market widgets — plotting your own data (CSV)

Every Stock* chart widget in widgets/components/ renders from one shared type, xframe::OHLCVSeries (widgets/components/StockData.h). Out of the box each widget ships with deterministic synthetic template data (see Template data below) so demos and screenshots are reproducible with no network and no live market data. To plot your own data, load a CSV file into that same series type — the loader lives in StockData.h next to the model, and every series-plotting widget has a one-call way to use it.

Which widgets this covers

23 widgets plot a data series and take CSV input:

Group Widgets CSV entry point
OHLC / price charts (8) StockCandlestickChart, StockOHLCBarChart, StockLineChart, StockAreaChart, StockHeikinAshi, StockRenko, StockHollowCandles, StockBaselineChart load_csv(path, error)
Volume / flow indicators (7) StockVolumeBars, StockVolumeCandles, StockVolumeProfile, StockAccumulationDistribution, StockMoneyFlowChart, StockOBVChart, StockVWAP load_csv(path, error)
Comparative plotting (8) StockOverlayChart, StockMultiSymbolChart, StockIndexedComparison, StockRelativePerformance, StockRatioChart, StockSpreadChart, StockCorrelationView, StockSectorComparison add_series_csv(path, name, error)
Indicators (250) All Ind* widgets (IndSMA, IndRSI, IndMACD, IndBollingerBands, …) load_csv(path, error) — recomputes the indicator lines from the file

One group is not covered, on purpose:

  • Drawing / annotation tools (14) — StockTrendline, StockFibRetracement, StockFibExtension, StockPitchfork, StockParallelChannel, StockRectangle, StockEllipse, StockArrow, StockBrush, StockHorizontalLine, StockVerticalLine, StockMeasureTool, StockPriceLabel, StockTextAnnotation — take coordinates (add_point, set_anchor, set_high_low, set_pivots), not a data series. They do draw a background candle series (their set_series), which you can replace with set_series(xframe::load_ohlcv_csv(path, err)), but they have no load_csv of their own because there is no series to plot.

The CSV format

One bar per line:

date,open,high,low,close,volume
2026-11-02,150.00,151.20,149.40,150.60,1200000
2026-11-03,150.60,152.10,150.10,151.80,980000
Rule Detail
Header row Optional. When the first non-empty line is a header, columns are matched by name and may appear in any order. Recognised names (case-insensitive): date, timestamp, time, window_start, open, high, low, close, volume (or vol). Anything else (ticker, transactions, adj_close, …) is ignored — Massive aggregates exports load as-is. Without a header the columns are positional: date,open,high,low,close,volume.
Required columns open, high, low, close. A header missing any of these is an error.
Dates Read as UTC: YYYY-MM-DD, YYYY/MM/DD, YYYY-MM-DD HH:MM:SS (or a T separator, optional trailing Z), or a bare epoch timestamp: seconds (≥ 1e9), milliseconds (≥ 1e12), nanoseconds (≥ 1e15, Massive window_start).
volume Optional, defaults to 0.
Missing date A missing date column — or a headerless 5-column file open,high,low,close,volume — gets sequential daily timestamps starting 2026-01-01 UTC, one day per bar.
Blank lines Skipped.
Malformed rows Skipped and counted (see skipped below); the rest of the file still loads.
Quoting / line endings Double-quoted fields ("" is a literal quote), CRLF, and a UTF-8 BOM are all handled.
Well-formed bars Should satisfy high >= max(open, close) and low <= min(open, close). The loader keeps the file's values as-is and does not repair them.

Loader API (xframe namespace, StockData.h)

// From a file. Returns the series; empty + `error` set on failure
// (unreadable file, header missing open/high/low/close, no valid rows).
OHLCVSeries load_ohlcv_csv(const std::string& path, std::string& error,
                           int* skipped = nullptr);

// From text (same rules; used by the unit tests).
OHLCVSeries parse_ohlcv_csv_text(const std::string& text, std::string& error,
                                 int* skipped = nullptr);

skipped (when given) receives the number of malformed rows skipped. error is empty on success — that is the success test, there is no separate boolean.

Template data

What each widget draws before you replace the data — all deterministic, all reproducible, no network:

  • OHLC group (8): constructor default xframe::make_seeded_series(250) — 250 daily bars from 2026-01-01 UTC, random walk starting at 100.0, default seed 42. Same (n, seed) gives the identical series on every run and every platform.
  • Volume / flow indicators (7): constructor default xframe::make_seeded_series(60, 42) — 60 bars, same generator. StockHeikinAshi rebuilds its Heikin-Ashi candles and StockRenko rebuilds its bricks from whatever series is set; StockBaselineChart resets its baseline to the first bar's close.
  • Indicators (250): constructor default xframe::make_seeded_series(250) — 250 bars, same generator as the OHLC group. Each widget recomputes its own lines from that series in the constructor (see Indicators below); loading a CSV replaces the series and recomputes the lines.
  • Comparative widgets (8): the constructor seeds two or three named series — SYM-A (make_seeded_series(60, 42)), SYM-B (seed 7), SYM-C (seed 99) — so the multi-line / comparison rendering is visible immediately. Different seeds stand in for different symbols.

The template series is only a stand-in. It is never refreshed, never fetched, and it is not live market data.

Replacing the data

Single-series charts: load_csv

#include "StockCandlestickChart.h"

StockCandlestickChart w(display, screen, window, gc, &styles,
                        20, 20, 720, 480);
std::string err;
if (!w.load_csv("aapl_30d.csv", err)) {
    std::fprintf(stderr, "cannot load CSV: %s\n", err.c_str());
    // The old series is untouched: the chart keeps drawing what it had.
} else {
    w.draw();  // now plots the CSV bars; view resets to show all of them
}

load_csv is the same shape on all 15 single-series widgets — and on all 250 Ind* indicators (see Indicators): (StockCandlestickChart, StockOHLCBarChart, StockLineChart, StockAreaChart, StockHeikinAshi, StockRenko, StockHollowCandles, StockBaselineChart, StockVolumeBars, StockVolumeCandles, StockVolumeProfile, StockAccumulationDistribution, StockMoneyFlowChart, StockOBVChart, StockVWAP). It loads the file with xframe::load_ohlcv_csv and, on success, calls set_series, which resets the view (view_first_ = 0, view_count_ = 0) and rebuilds derived data (Heikin-Ashi candles, Renko bricks, the baseline). On failure it returns false and leaves the series unchanged.

The same thing spelled out, for when you already have a series in hand (from the loader, from make_seeded_series, or built by hand):

std::string err;
auto series = xframe::load_ohlcv_csv("aapl_30d.csv", err);
if (err.empty()) w.set_series(series);   // replaces the data, resets view

Or pass the loaded series straight to the constructor:

auto series = xframe::load_ohlcv_csv("aapl_30d.csv", err);
StockLineChart w(display, screen, window, gc, &styles,
                 20, 20, 720, 480, series);

Multi-series charts: add_series_csv

#include "StockMultiSymbolChart.h"

StockMultiSymbolChart w(display, screen, window, gc, &styles,
                        20, 20, 720, 480);
w.clear_series();  // drop the SYM-A/SYM-B/SYM-C template series
std::string err;
w.add_series_csv("aapl_30d.csv", "AAPL", err);   // returns false on error
w.add_series_csv("msft_30d.csv", "MSFT", err);   // each file is one symbol
w.draw();

add_series_csv(path, name, error) is the same shape on all 8 comparative widgets (StockOverlayChart, StockMultiSymbolChart, StockIndexedComparison, StockRelativePerformance, StockRatioChart, StockSpreadChart, StockCorrelationView, StockSectorComparison). It loads the file and appends it as a named series (colour picked from the palette in order). On failure it returns false and appends nothing. clear_series() removes all series — call it first when you want only your own symbols, since the constructor pre-loads the template ones.

Clear / populate workflow

w.set_series(xframe::OHLCVSeries{});  // single-series: clear the chart
w.clear_series();                      // single-series: same thing
// multi-series:
w.clear_series();                      // remove every series
w.add_series_csv("aapl_30d.csv", "AAPL", err);  // populate, one file per symbol

There is no add_point: bars are replaced wholesale with set_series / load_csv (or appended per-symbol with add_series_csv). item_count() reports how many items are plotted — bars for most widgets, Heikin-Ashi candles for StockHeikinAshi, bricks for StockRenko (30 CSV bars build 25 bricks at the default brick size), and the longest series length for the comparative widgets.

Indicators (load_csv / set_series)

All 250 Ind* widgets take CSV data the same way the single-series charts do — load_csv, set_series, clear_series, series() — with one difference: an indicator does not plot the bars themselves, it plots lines computed from the bars (SMA, RSI, Bollinger bands, …), so setting a series recomputes those lines from the new bars.

#include "IndSMA.h"

IndSMA w(display, screen, window, gc, &styles, 20, 20, 760, 520);
std::string err;
if (!w.load_csv("aapl_30d.csv", err)) {
    std::fprintf(stderr, "cannot load CSV: %s\n", err.c_str());
    // The old series is untouched: the widget keeps drawing what it had.
} else {
    w.draw();  // now plots the SMA of the CSV closes; view resets
}

How it works, per widget:

  • The constructor still computes the lines once, from the constructor series (default: the seeded template, 250 bars). set_series stores the new series, resets the view (reset_view(), where the widget has one), and recomputes the lines with the widget's own formula and its stored parameters (period, multiplier, fast/slow, …) — the parameters that used to be constructor-only are now stored as members, so a reloaded series uses the same settings the widget was built with.
  • load_csv loads the file with xframe::load_ohlcv_csv and, on success, calls set_series. On failure it returns false and leaves the series — and the lines — unchanged.
  • clear_series() empties the series (and the lines); the widget draws its empty frame. The seeded template is only the constructor default — clear_series does not restore it. To get the template back, call set_series(xframe::make_seeded_series(250)).
  • Passing a loaded series to the constructor still works, exactly as before:
std::string err;
auto series = xframe::load_ohlcv_csv("aapl_30d.csv", err);
IndSMA w(display, screen, window, gc, &styles, 20, 20, 760, 520, series);
w.draw();

Two things to know:

  • Line colours reset on recompute. set_line_color(i, c) tints are part of the rebuilt lines, so a set_series / load_csv restores the widget's default line colours. Re-apply tints after loading if you customised them.
  • Warm-up bars stay NaN. A 30-row CSV into a period-20 indicator leaves the first 19 line values NaN, exactly as the template series does — only the values differ, never the shape of the computation.

The designer's own CSV support (different thing)

The LightGUI designer app (src/main.cpp) has its own, separate CSV reader for its StockChart preview: the data-file Inspector property loads a Massive aggregates CSV (columns matched by header name: ticker,volume,open,close,high,low,window_start,transactions) into the designer's preview chart, with compare-files for comparison series. That loader lives in the designer, not in the widget library, and it is not what the widgets use. The widget-level loader above accepts the Massive format too (same header-name matching, window_start in nanoseconds), plus the plain date,open,high,low,close,volume layout.

Limits

  • No streaming / live updates: the whole file is read at once and the widget plots the resulting series. To show new bars, re-load the file and call load_csv / set_series again.
  • No network, no API keys, no live market data anywhere in the widgets: the loader reads a local file only.
  • A file with no valid rows is an error, not an empty chart: load_csv returns false and the previous series stays in place.
  • Dates are read as UTC; intraday times (HH:MM:SS) are kept in the timestamp but the charts plot bars by index, not by clock time — two bars 1 minute apart and two bars 1 day apart take the same horizontal space.
  • Very large files are fine in memory terms (one OHLCV per row, 48 bytes), but the widgets draw every visible bar, so tens of thousands of bars will be slow to draw and to pan — use set_view_first / set_view_count to show a window.

Tests and fixtures

  • tests/data/ohlcv_sample.csv — 30 daily bars, 2026-11-02 → 2026-12-11 (weekdays), gentle rise, sharp drop, recovery; first close 150.60, last close 152.25. tests/data/ohlcv_sample_b.csv — a second symbol with the same dates (first close 319.38, last close 311.07), used as the second series for the comparative widgets.
  • widgets/tests/csv_unit_test.cpp — parser unit tests: the two fixtures, Massive format, headerless 5- and 6-column files, reordered headers, all four date forms, malformed rows skipped + counted, CRLF / BOM / quoted fields, and the error cases (missing file, empty input, header missing close, no valid rows).
  • widgets/tests/test_stock_csv.py — end-to-end driver: rebuilds every in-scope demo, screenshots the template-data render, then screenshots a harness that loads the fixture via load_csv / add_series_csv and checks the CSV shot is non-blank, differs from the template shot (the plot follows the file), reports 30 items, and that a missing file exits without touching the series. Result: 23/23 widgets PASS.
  • widgets/tests/ind_csv_harness.cpp + widgets/tests/test_ind_csv.py — the same treatment for all 250 Ind* indicators: per-widget harness (template dump → load_csv 30-row fixture → set_series 1170-row Massive fixture → failed load leaves the series untouched → clear_series empties lines and draws clean) plus template-vs-CSV screenshots for a 39-widget sample and a rebuild of all 250 demo mains. Result: 250/250 harnesses build, 250/250 numeric PASS, 39/39 screenshots PASS, 250/250 demo mains build. (One generator bug found en route: a signal parameter colliding with a result-struct field was rewritten to result.signal_ in IndMACD — fixed, and the generator now skips identifiers after . / ->.)