Stock chart CSV data: loader in StockData.h, load_csv/add_series_csv on 23 widgets, docs + tests

- xframe::load_ohlcv_csv / parse_ohlcv_csv_text in StockData.h:
  date,open,high,low,close,volume, optional header matched by name
  (Massive exports load as-is), YYYY-MM-DD / ISO / epoch s-ms-ns dates,
  volume optional, malformed rows skipped + counted, error string out.
- 15 single-series widgets gain load_csv() + clear_series();
  8 comparative widgets gain add_series_csv(); failure leaves the
  series untouched. Drawing tools intentionally excluded (coordinates,
  not series); Ind* widgets take CSV only via the constructor.
- Fixtures tests/data/ohlcv_sample.csv (+ _b, 30 rows each) and
  widgets/tests/csv_unit_test.cpp + test_stock_csv.py (23/23 PASS:
  CSV shot differs from template shot, 30 items, bad path exits 2).
- docs/stock-market-csv-data.md + CSV sections in the stock group docs.
This commit is contained in:
cnmcdee committed 2026-12-02 10:15:50 +00:00
1 parent 7d7fa6cfbc
commit 099733b27d
33 files changed
+1349

No files matched your search

+25
View File
@@ -290,3 +290,28 @@ hover/click/key, and exits cleanly via `WM_DELETE_WINDOW`. Result:
this widget does *not* cumulate — each bar stands alone. The vertical
scale is money-flow units (price × volume), not volume, so bar heights
are not comparable with `StockVolumeBars`.
## Loading your own data (CSV)
The template series above are only stand-ins (`SYM-A`/`SYM-B`/`SYM-C`
seeded series). Every widget in this group takes real data from CSV
files — `date,open,high,low,close,volume`, header optional, dates as
`YYYY-MM-DD` or epoch timestamps — through
`xframe::load_ohlcv_csv` in `widgets/components/StockData.h` and the
widget's own `add_series_csv(path, name, error)`:
```cpp
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); // one file per symbol
w.add_series_csv("msft_30d.csv", "MSFT", err);
w.draw();
```
Single-series widgets in this group (`StockVolumeBars`,
`StockVolumeCandles`, `StockVolumeProfile`, `StockAccumulationDistribution`,
`StockMoneyFlowChart`, `StockOBVChart`, `StockVWAP`) use `load_csv(path,
error)` instead, and `clear_series()` empties them. Full format spec,
template-data notes, the clear/populate workflow and limits:
[stock-market-csv-data.md](stock-market-csv-data.md).
+251
View File
@@ -0,0 +1,251 @@
# 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](#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)` |
Two groups are **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 250 `Ind*` indicator widgets** take a series only through their
constructor — they have no `set_series` at all. Pass a loaded series
there (see [Indicators](#indicators-constructor-only) below). Adding a
`set_series` to all 250 is a separate job: each one recomputes its own
lines from the series in its constructor, so there is no single generic
setter to add.
## The CSV format
One bar per line:
```csv
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`)
```cpp
// 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.
- **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`
```cpp
#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
(`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):
```cpp
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:
```cpp
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`
```cpp
#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
```cpp
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 (constructor only)
The 250 `Ind*` widgets have no `set_series`; give them the loaded series
at construction:
```cpp
#include "IndSMA.h"
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();
```
The indicator is computed from the series in the constructor, so a series
loaded from CSV plots exactly like the seeded template one — only the
values differ.
## 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**.
+17
View File
@@ -336,3 +336,20 @@ Unclear from the header: differences are signed (reversed anchors give
negative values); `pct_diff()` returns 0 if the first anchor's price is
0; the info box is placed above the higher anchor and clamped into the
plot, so it can overlap the line on short measurements.
## Plotting data vs drawing on top of it
These tools take **coordinates, not a data series** — `add_point`,
`set_anchor`, `set_high_low`, `set_pivots` — so there is no CSV loader
on them. They do draw a background candle series (their `set_series`,
seeded template data by default), which you can replace with your own
CSV data through the shared loader:
```cpp
std::string err;
auto series = xframe::load_ohlcv_csv("aapl_30d.csv", err);
if (err.empty()) w.set_series(series); // background candles from CSV
```
Format spec (`date,open,high,low,close,volume`, header optional):
[stock-market-csv-data.md](stock-market-csv-data.md).
+20
View File
@@ -247,3 +247,23 @@ w.draw();
StockBaselineChart w(display, screen, window, gc, &styles, 20, 20, 720, 480, xframe::make_seeded_series(250));
w.draw();
```
## Loading your own data (CSV)
The template series above is only a stand-in. Every widget in this group
takes real data from a CSV file — `date,open,high,low,close,volume`, header
optional, dates as `YYYY-MM-DD` or epoch timestamps — through
`xframe::load_ohlcv_csv` in `widgets/components/StockData.h` and the
widget's own `load_csv(path, error)`:
```cpp
StockCandlestickChart w(display, screen, window, gc, &styles, 20, 20, 720, 480);
std::string err;
if (!w.load_csv("aapl_30d.csv", err)) { /* old series untouched */ }
w.draw();
```
`load_csv` replaces the series and resets the view; `clear_series()`
empties the chart. Full format spec, template-data notes, the
clear/populate workflow and limits:
[stock-market-csv-data.md](stock-market-csv-data.md).
+10
View File
@@ -65,6 +65,16 @@ auto series = xframe::make_seeded_series(250, 42); // 250 daily bars
auto closes = xframe::series_closes(series);
```
## Loading your own data (CSV)
The seeded series is only a stand-in. Real data comes from a CSV file
(`date,open,high,low,close,volume`, header optional) via
`xframe::load_ohlcv_csv` in `StockData.h`: single-series widgets expose
`load_csv(path, error)`, comparative widgets expose
`add_series_csv(path, name, error)`. Full spec, template-data notes and
the clear/populate workflow:
[stock-market-csv-data.md](stock-market-csv-data.md).
## How indicators are computed
Every indicator compute function returns a vector the same length as
+31
View File
@@ -0,0 +1,31 @@
date,open,high,low,close,volume
2026-11-02,150.00,150.78,149.40,150.60,915898
2026-11-03,150.60,151.98,150.50,151.62,1611897
2026-11-04,151.62,152.06,151.51,151.64,945140
2026-11-05,151.64,153.19,151.48,152.44,1157182
2026-11-06,152.44,154.50,151.90,153.64,1434688
2026-11-09,153.64,155.63,152.86,155.54,1263374
2026-11-10,155.54,155.93,155.23,155.78,2105802
2026-11-11,155.78,156.63,155.19,156.09,1395836
2026-11-12,156.09,157.24,155.99,157.14,1129533
2026-11-13,157.14,158.86,156.82,158.45,1736898
2026-11-16,158.45,159.61,157.72,159.31,1918391
2026-11-17,159.31,160.29,158.81,159.75,2200219
2026-11-18,159.75,160.04,157.37,158.25,988905
2026-11-19,158.25,158.94,155.76,155.94,1582340
2026-11-20,155.94,156.56,151.94,152.64,1716841
2026-11-23,152.64,152.96,150.88,151.52,1750991
2026-11-24,151.52,151.96,148.87,149.63,2311489
2026-11-25,149.63,150.24,147.36,147.46,1922387
2026-11-26,147.46,149.21,146.71,148.32,1255352
2026-11-27,148.32,149.25,148.25,148.63,1538712
2026-11-30,148.63,148.78,148.38,148.48,2029172
2026-12-01,148.48,148.74,147.87,148.25,2194275
2026-12-02,148.25,148.68,147.40,147.92,2213414
2026-12-03,147.92,149.92,147.63,149.14,1464474
2026-12-04,149.14,150.19,148.28,149.39,1041473
2026-12-07,149.39,149.64,149.01,149.26,1575940
2026-12-08,149.26,150.27,149.21,150.00,1470314
2026-12-09,150.00,150.81,149.14,150.28,1904789
2026-12-10,150.28,151.43,149.66,150.86,886388
2026-12-11,150.86,152.96,150.07,152.25,2076596
1 date open high low close volume
2 2026-11-02 150.00 150.78 149.40 150.60 915898
3 2026-11-03 150.60 151.98 150.50 151.62 1611897
4 2026-11-04 151.62 152.06 151.51 151.64 945140
5 2026-11-05 151.64 153.19 151.48 152.44 1157182
6 2026-11-06 152.44 154.50 151.90 153.64 1434688
7 2026-11-09 153.64 155.63 152.86 155.54 1263374
8 2026-11-10 155.54 155.93 155.23 155.78 2105802
9 2026-11-11 155.78 156.63 155.19 156.09 1395836
10 2026-11-12 156.09 157.24 155.99 157.14 1129533
11 2026-11-13 157.14 158.86 156.82 158.45 1736898
12 2026-11-16 158.45 159.61 157.72 159.31 1918391
13 2026-11-17 159.31 160.29 158.81 159.75 2200219
14 2026-11-18 159.75 160.04 157.37 158.25 988905
15 2026-11-19 158.25 158.94 155.76 155.94 1582340
16 2026-11-20 155.94 156.56 151.94 152.64 1716841
17 2026-11-23 152.64 152.96 150.88 151.52 1750991
18 2026-11-24 151.52 151.96 148.87 149.63 2311489
19 2026-11-25 149.63 150.24 147.36 147.46 1922387
20 2026-11-26 147.46 149.21 146.71 148.32 1255352
21 2026-11-27 148.32 149.25 148.25 148.63 1538712
22 2026-11-30 148.63 148.78 148.38 148.48 2029172
23 2026-12-01 148.48 148.74 147.87 148.25 2194275
24 2026-12-02 148.25 148.68 147.40 147.92 2213414
25 2026-12-03 147.92 149.92 147.63 149.14 1464474
26 2026-12-04 149.14 150.19 148.28 149.39 1041473
27 2026-12-07 149.39 149.64 149.01 149.26 1575940
28 2026-12-08 149.26 150.27 149.21 150.00 1470314
29 2026-12-09 150.00 150.81 149.14 150.28 1904789
30 2026-12-10 150.28 151.43 149.66 150.86 886388
31 2026-12-11 150.86 152.96 150.07 152.25 2076596
+31
View File
@@ -0,0 +1,31 @@
date,open,high,low,close,volume
2026-11-02,320.00,320.64,318.79,319.38,1566560
2026-11-03,319.38,320.10,318.12,318.86,1619929
2026-11-04,318.86,319.17,318.81,318.92,1393674
2026-11-05,318.92,319.25,318.20,319.14,1171604
2026-11-06,319.14,319.23,317.76,318.66,1981900
2026-11-09,318.66,320.03,318.58,319.46,1326286
2026-11-10,319.46,319.66,318.60,319.51,1389514
2026-11-11,319.51,320.25,318.71,318.87,2284710
2026-11-12,318.87,319.39,318.49,318.83,1575525
2026-11-13,318.83,318.91,317.46,318.25,1175785
2026-11-16,318.25,319.09,317.38,318.86,2230345
2026-11-17,318.86,320.12,318.32,319.42,1967611
2026-11-18,319.42,319.87,315.59,316.34,1121727
2026-11-19,316.34,317.14,314.94,315.34,1384352
2026-11-20,315.34,315.72,312.21,313.11,1418549
2026-11-23,313.11,313.24,309.12,309.78,2388517
2026-11-24,309.78,310.25,307.15,307.67,1997081
2026-11-25,307.67,308.24,304.33,304.85,1796196
2026-11-26,304.85,305.04,304.38,304.73,2283317
2026-11-27,304.73,305.52,304.42,304.96,965237
2026-11-30,304.96,305.70,303.89,304.60,1399800
2026-12-01,304.60,306.16,303.79,305.54,2333248
2026-12-02,305.54,306.78,304.67,305.89,1744830
2026-12-03,305.89,307.71,305.52,307.24,1195532
2026-12-04,307.24,308.77,307.13,308.58,2088450
2026-12-07,308.58,310.17,307.82,309.71,883477
2026-12-08,309.71,310.05,309.30,309.75,1073007
2026-12-09,309.75,310.09,308.59,309.40,2373515
2026-12-10,309.40,310.93,309.14,310.47,2334204
2026-12-11,310.47,311.74,310.40,311.07,1139346
1 date open high low close volume
2 2026-11-02 320.00 320.64 318.79 319.38 1566560
3 2026-11-03 319.38 320.10 318.12 318.86 1619929
4 2026-11-04 318.86 319.17 318.81 318.92 1393674
5 2026-11-05 318.92 319.25 318.20 319.14 1171604
6 2026-11-06 319.14 319.23 317.76 318.66 1981900
7 2026-11-09 318.66 320.03 318.58 319.46 1326286
8 2026-11-10 319.46 319.66 318.60 319.51 1389514
9 2026-11-11 319.51 320.25 318.71 318.87 2284710
10 2026-11-12 318.87 319.39 318.49 318.83 1575525
11 2026-11-13 318.83 318.91 317.46 318.25 1175785
12 2026-11-16 318.25 319.09 317.38 318.86 2230345
13 2026-11-17 318.86 320.12 318.32 319.42 1967611
14 2026-11-18 319.42 319.87 315.59 316.34 1121727
15 2026-11-19 316.34 317.14 314.94 315.34 1384352
16 2026-11-20 315.34 315.72 312.21 313.11 1418549
17 2026-11-23 313.11 313.24 309.12 309.78 2388517
18 2026-11-24 309.78 310.25 307.15 307.67 1997081
19 2026-11-25 307.67 308.24 304.33 304.85 1796196
20 2026-11-26 304.85 305.04 304.38 304.73 2283317
21 2026-11-27 304.73 305.52 304.42 304.96 965237
22 2026-11-30 304.96 305.70 303.89 304.60 1399800
23 2026-12-01 304.60 306.16 303.79 305.54 2333248
24 2026-12-02 305.54 306.78 304.67 305.89 1744830
25 2026-12-03 305.89 307.71 305.52 307.24 1195532
26 2026-12-04 307.24 308.77 307.13 308.58 2088450
27 2026-12-07 308.58 310.17 307.82 309.71 883477
28 2026-12-08 309.71 310.05 309.30 309.75 1073007
29 2026-12-09 309.75 310.09 308.59 309.40 2373515
30 2026-12-10 309.40 310.93 309.14 310.47 2334204
31 2026-12-11 310.47 311.74 310.40 311.07 1139346
@@ -75,6 +75,17 @@ set_series(xframe::make_seeded_series(60, 42));
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
void set_symbol(const std::string& s) { symbol_ = s; }
std::string symbol() { return symbol_; }
int series_count() { return series_.empty() ? 0 : 1; }
@@ -99,6 +99,17 @@ public:
double get_y_max() { return y_max_; }
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
const xframe::OHLCVSeries& series() const { return series_; }
int item_count() { return (int)series_.size(); }
void set_y_range(double lo, double hi) { auto_y_ = false; y_min_ = lo; y_max_ = hi; }
@@ -107,6 +107,17 @@ public:
double get_baseline() { return baseline_; }
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; if (!series_.empty()) baseline_ = series_[0].close; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
const xframe::OHLCVSeries& series() const { return series_; }
int item_count() { return (int)series_.size(); }
void set_y_range(double lo, double hi) { auto_y_ = false; y_min_ = lo; y_max_ = hi; }
@@ -90,6 +90,17 @@ public:
double get_y_max() { return y_max_; }
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
const xframe::OHLCVSeries& series() const { return series_; }
int item_count() { return (int)series_.size(); }
void set_y_range(double lo, double hi) { auto_y_ = false; y_min_ = lo; y_max_ = hi; }
@@ -88,6 +88,15 @@ add_series("SYM-A", xframe::make_seeded_series(60, 42));
void add_series(const std::string& name, const xframe::OHLCVSeries& s) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = kPalette[series_.size() % 8]; series_.push_back(ns); }
void add_series(const std::string& name, const xframe::OHLCVSeries& s, Srgb color) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = color; series_.push_back(ns); }
void clear_series() { series_.clear(); view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and append it as a named series. Returns false and appends nothing
// on error; `error` explains why.
bool add_series_csv(const std::string& path, const std::string& name, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
add_series(name, s);
return true;
}
int series_count() { return (int)series_.size(); }
int item_count() { size_t n = 0; for (auto& s : series_) n = std::max(n, s.data.size()); return (int)n; }
std::vector<double> closes_of(int i) { return xframe::series_closes(series_[i].data); }
+269
View File
@@ -9,6 +9,10 @@
#include <cmath>
#include <cstdint>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
namespace xframe {
@@ -113,4 +117,269 @@ inline std::vector<double> series_typical(const OHLCVSeries &s) {
return v;
}
// ---- CSV loading ---------------------------------------------------------
// load_ohlcv_csv / parse_ohlcv_csv_text: read OHLCV bars from a CSV file
// (or string) into the shared OHLCVSeries model, so any chart widget can
// plot a real data file instead of the seeded template series:
//
// std::string err;
// auto series = xframe::load_ohlcv_csv("aapl_30d.csv", err);
// if (!err.empty()) { /* report err; series is empty */ }
// chart.set_series(series); // or chart.load_csv(path, err)
//
// Format (one bar per line):
// date,open,high,low,close,volume
// - A header row is 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. Anything else (ticker, transactions,
// adj_close, ...) is ignored, so Massive aggregates exports load as-is.
// Without a header the columns are positional:
// date,open,high,low,close,volume.
// - Dates are read as UTC: YYYY-MM-DD, YYYY/MM/DD, YYYY-MM-DD HH:MM:SS
// (or a T separator, optional trailing Z), or an epoch timestamp:
// seconds (>= 1e9), milliseconds (>= 1e12), nanoseconds (>= 1e15,
// Massive window_start).
// - volume is optional and defaults to 0. A missing date column -- or a
// headerless 5-column file open,high,low,close,volume -- gets sequential
// daily timestamps starting 2026-01-01 UTC.
// - Blank lines are skipped; a row that does not parse is skipped and
// counted in *skipped. On failure the returned series is empty and
// `error` explains why: unreadable file, missing open/high/low/close
// columns, or no valid rows.
// - Well-formed rows satisfy high >= max(open, close) and
// low <= min(open, close); the loader keeps the file's values as-is
// and does not repair them.
namespace detail {
// Days since 1970-01-01 for a civil date (Howard Hinnant's algorithm;
// pure arithmetic, no timezone, no mktime).
inline std::int64_t stock_days_from_civil(int y, unsigned m, unsigned d) {
y -= m <= 2;
const std::int64_t era = (y >= 0 ? y : y - 399) / 400;
const unsigned yoe = static_cast<unsigned>(y - era * 400);
const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + static_cast<std::int64_t>(doe) - 719468;
}
inline std::string stock_trim(const std::string& s) {
size_t b = s.find_first_not_of(" \t\r\n");
if (b == std::string::npos) return std::string();
size_t e = s.find_last_not_of(" \t\r\n");
return s.substr(b, e - b + 1);
}
// Split one CSV line on commas, honouring double-quoted fields ("" is a
// literal quote). Returned fields are trimmed; surrounding quotes removed.
inline std::vector<std::string> stock_split_csv(const std::string& line) {
std::vector<std::string> fields;
std::string cur;
bool quoted = false;
for (size_t i = 0; i < line.size(); ++i) {
char c = line[i];
if (quoted) {
if (c == '"') {
if (i + 1 < line.size() && line[i + 1] == '"') { cur += '"'; ++i; }
else quoted = false;
} else cur += c;
} else if (c == '"') {
quoted = true;
} else if (c == ',') {
fields.push_back(stock_trim(cur));
cur.clear();
} else cur += c;
}
fields.push_back(stock_trim(cur));
return fields;
}
inline bool stock_parse_double(const std::string& s, double& out) {
if (s.empty()) return false;
char* end = nullptr;
out = std::strtod(s.c_str(), &end);
return end != s.c_str() && *end == '\0';
}
inline bool stock_parse_int(const std::string& s, std::int64_t& out) {
if (s.empty()) return false;
size_t i = (s[0] == '-' || s[0] == '+') ? 1 : 0;
if (i >= s.size()) return false;
for (size_t j = i; j < s.size(); ++j)
if (s[j] < '0' || s[j] > '9') return false;
char* end = nullptr;
out = std::strtoll(s.c_str(), &end, 10);
return end != s.c_str() && *end == '\0';
}
// Parse a date into epoch seconds (UTC). Accepts YYYY-MM-DD, YYYY/MM/DD,
// optional " HH:MM[:SS]" or "THH:MM[:SS]" (+ trailing Z), or a bare epoch
// timestamp (s / ms / ns by magnitude).
inline bool stock_parse_date(const std::string& s, std::int64_t& out) {
if (s.size() >= 10 && (s[4] == '-' || s[4] == '/') && s[7] == s[4]) {
std::int64_t y = 0, mo = 0, d = 0;
if (!stock_parse_int(s.substr(0, 4), y) ||
!stock_parse_int(s.substr(5, 2), mo) ||
!stock_parse_int(s.substr(8, 2), d))
return false;
if (y < 1970 || y > 2100 || mo < 1 || mo > 12 || d < 1 || d > 31)
return false;
std::int64_t secs = stock_days_from_civil((int)y, (unsigned)mo,
(unsigned)d) * 86400;
if (s.size() > 10 && (s[10] == ' ' || s[10] == 'T')) {
std::int64_t hh = 0, mm = 0, ss = 0;
if (s.size() < 16) return false;
if (!stock_parse_int(s.substr(11, 2), hh) ||
!stock_parse_int(s.substr(14, 2), mm))
return false;
if (s.size() >= 19 && s[16] == ':') {
if (!stock_parse_int(s.substr(17, 2), ss)) return false;
}
if (hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 60)
return false;
secs += hh * 3600 + mm * 60 + ss;
}
out = secs;
return true;
}
std::int64_t v = 0;
if (!stock_parse_int(s, v)) return false;
if (v >= 1000000000000000LL) v /= 1000000000LL; // ns -> s
else if (v >= 1000000000000LL) v /= 1000; // ms -> s
if (v < 1000000000LL) return false; // before 2001: not a date
out = v;
return true;
}
inline std::string stock_lower(std::string s) {
for (char& c : s)
if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
return s;
}
} // namespace detail
// Parse OHLCV bars from CSV text. Returns the series (empty + `error` set
// on failure). `skipped` (if given) receives the count of malformed rows
// that were skipped.
inline OHLCVSeries parse_ohlcv_csv_text(const std::string& text,
std::string& error,
int* skipped = nullptr) {
error.clear();
if (skipped) *skipped = 0;
OHLCVSeries out;
std::string body = text;
// Strip a UTF-8 BOM.
if (body.size() >= 3 && (unsigned char)body[0] == 0xEF &&
(unsigned char)body[1] == 0xBB && (unsigned char)body[2] == 0xBF)
body = body.substr(3);
std::istringstream in(body);
std::string line;
// Column map: -1 = absent. Positional default is date,open,high,low,
// close,volume.
int c_date = 0, c_open = 1, c_high = 2, c_low = 3, c_close = 4, c_vol = 5;
bool have_header = false;
bool seen_first = false;
const std::int64_t day0 = 1767225600; // 2026-01-01 00:00:00 UTC
auto skip_row = [&]() { if (skipped) ++(*skipped); };
while (std::getline(in, line)) {
if (detail::stock_trim(line).empty()) continue;
std::vector<std::string> f = detail::stock_split_csv(line);
if (!seen_first) {
seen_first = true;
std::int64_t probe = 0;
double num = 0;
bool first_is_date = detail::stock_parse_date(f[0], probe);
bool first_is_num = detail::stock_parse_double(f[0], num);
if (!first_is_date && !first_is_num) {
// Header row: match columns by name.
have_header = true;
c_date = c_open = c_high = c_low = c_close = c_vol = -1;
for (size_t i = 0; i < f.size(); ++i) {
std::string n = detail::stock_lower(f[i]);
if (n == "date" || n == "timestamp" || n == "time" ||
n == "window_start") c_date = (int)i;
else if (n == "open") c_open = (int)i;
else if (n == "high") c_high = (int)i;
else if (n == "low") c_low = (int)i;
else if (n == "close") c_close = (int)i;
else if (n == "volume" || n == "vol") c_vol = (int)i;
}
if (c_open < 0 || c_high < 0 || c_low < 0 || c_close < 0) {
std::string missing;
if (c_open < 0) missing += " open";
if (c_high < 0) missing += " high";
if (c_low < 0) missing += " low";
if (c_close < 0) missing += " close";
error = "CSV header is missing required column(s):" + missing;
return OHLCVSeries{};
}
continue;
}
// No header: positional. A 5-field numeric row is
// open,high,low,close,volume (no date column).
if (!first_is_date && f.size() == 5) {
c_date = -1; c_open = 0; c_high = 1; c_low = 2; c_close = 3; c_vol = 4;
}
}
int need = std::max(std::max(c_open, c_high),
std::max(c_low, c_close));
if (c_date >= 0) need = std::max(need, c_date);
if (c_vol >= 0) need = std::max(need, c_vol);
if ((int)f.size() <= need) { skip_row(); continue; }
OHLCV b;
double o = 0, h = 0, l = 0, c = 0, v = 0;
if (!detail::stock_parse_double(f[(size_t)c_open], o) ||
!detail::stock_parse_double(f[(size_t)c_high], h) ||
!detail::stock_parse_double(f[(size_t)c_low], l) ||
!detail::stock_parse_double(f[(size_t)c_close], c)) {
skip_row(); continue;
}
if (c_vol >= 0 && !f[(size_t)c_vol].empty() &&
!detail::stock_parse_double(f[(size_t)c_vol], v)) {
skip_row(); continue;
}
std::int64_t ts = day0 + (std::int64_t)out.size() * 86400;
if (c_date >= 0) {
if (!detail::stock_parse_date(f[(size_t)c_date], ts)) {
skip_row(); continue;
}
}
b.open = o; b.high = h; b.low = l; b.close = c; b.volume = v;
b.timestamp = ts;
out.push_back(b);
}
(void)have_header;
if (!seen_first) { error = "CSV file is empty"; return OHLCVSeries{}; }
if (out.empty()) {
error = "CSV file has no valid OHLCV rows";
if (skipped && *skipped > 0)
error += " (" + std::to_string(*skipped) + " row(s) skipped)";
return OHLCVSeries{};
}
return out;
}
// Load OHLCV bars from a CSV file at `path`. Returns the series (empty +
// `error` set on failure: unreadable file, bad header, or no valid rows).
inline OHLCVSeries load_ohlcv_csv(const std::string& path,
std::string& error,
int* skipped = nullptr) {
error.clear();
std::ifstream f(path);
if (!f) {
error = "cannot open CSV file: " + path;
return OHLCVSeries{};
}
std::ostringstream ss;
ss << f.rdbuf();
if (f.bad()) {
error = "cannot read CSV file: " + path;
return OHLCVSeries{};
}
return parse_ohlcv_csv_text(ss.str(), error, skipped);
}
} // namespace xframe
@@ -107,6 +107,17 @@ public:
double get_y_max() { return y_max_; }
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; rebuild_ha(); }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
const xframe::OHLCVSeries& series() const { return series_; }
int item_count() { return (int)ha_.size(); }
void set_y_range(double lo, double hi) { auto_y_ = false; y_min_ = lo; y_max_ = hi; }
@@ -90,6 +90,17 @@ public:
double get_y_max() { return y_max_; }
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
const xframe::OHLCVSeries& series() const { return series_; }
int item_count() { return (int)series_.size(); }
void set_y_range(double lo, double hi) { auto_y_ = false; y_min_ = lo; y_max_ = hi; }
@@ -77,6 +77,15 @@ add_series("SYM-A", xframe::make_seeded_series(60, 42));
void add_series(const std::string& name, const xframe::OHLCVSeries& s) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = kPalette[series_.size() % 8]; series_.push_back(ns); }
void add_series(const std::string& name, const xframe::OHLCVSeries& s, Srgb color) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = color; series_.push_back(ns); }
void clear_series() { series_.clear(); view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and append it as a named series. Returns false and appends nothing
// on error; `error` explains why.
bool add_series_csv(const std::string& path, const std::string& name, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
add_series(name, s);
return true;
}
int series_count() { return (int)series_.size(); }
int item_count() { size_t n = 0; for (auto& s : series_) n = std::max(n, s.data.size()); return (int)n; }
std::vector<double> closes_of(int i) { return xframe::series_closes(series_[i].data); }
@@ -95,6 +95,17 @@ public:
double get_y_max() { return y_max_; }
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
const xframe::OHLCVSeries& series() const { return series_; }
int item_count() { return (int)series_.size(); }
void set_y_range(double lo, double hi) { auto_y_ = false; y_min_ = lo; y_max_ = hi; }
@@ -81,6 +81,17 @@ set_series(xframe::make_seeded_series(60, 42));
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
void set_symbol(const std::string& s) { symbol_ = s; }
std::string symbol() { return symbol_; }
int series_count() { return series_.empty() ? 0 : 1; }
@@ -80,6 +80,15 @@ add_series("SYM-A", xframe::make_seeded_series(60, 42));
void add_series(const std::string& name, const xframe::OHLCVSeries& s) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = kPalette[series_.size() % 8]; series_.push_back(ns); }
void add_series(const std::string& name, const xframe::OHLCVSeries& s, Srgb color) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = color; series_.push_back(ns); }
void clear_series() { series_.clear(); view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and append it as a named series. Returns false and appends nothing
// on error; `error` explains why.
bool add_series_csv(const std::string& path, const std::string& name, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
add_series(name, s);
return true;
}
int series_count() { return (int)series_.size(); }
int item_count() { size_t n = 0; for (auto& s : series_) n = std::max(n, s.data.size()); return (int)n; }
std::vector<double> closes_of(int i) { return xframe::series_closes(series_[i].data); }
@@ -75,6 +75,17 @@ set_series(xframe::make_seeded_series(60, 42));
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
void set_symbol(const std::string& s) { symbol_ = s; }
std::string symbol() { return symbol_; }
int series_count() { return series_.empty() ? 0 : 1; }
@@ -90,6 +90,17 @@ public:
double get_y_max() { return y_max_; }
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
const xframe::OHLCVSeries& series() const { return series_; }
int item_count() { return (int)series_.size(); }
void set_y_range(double lo, double hi) { auto_y_ = false; y_min_ = lo; y_max_ = hi; }
@@ -74,6 +74,15 @@ add_series("SYM-A", xframe::make_seeded_series(60, 42));
void add_series(const std::string& name, const xframe::OHLCVSeries& s) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = kPalette[series_.size() % 8]; series_.push_back(ns); }
void add_series(const std::string& name, const xframe::OHLCVSeries& s, Srgb color) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = color; series_.push_back(ns); }
void clear_series() { series_.clear(); view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and append it as a named series. Returns false and appends nothing
// on error; `error` explains why.
bool add_series_csv(const std::string& path, const std::string& name, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
add_series(name, s);
return true;
}
int series_count() { return (int)series_.size(); }
int item_count() { size_t n = 0; for (auto& s : series_) n = std::max(n, s.data.size()); return (int)n; }
std::vector<double> closes_of(int i) { return xframe::series_closes(series_[i].data); }
@@ -76,6 +76,15 @@ add_series("SYM-A", xframe::make_seeded_series(60, 42));
void add_series(const std::string& name, const xframe::OHLCVSeries& s) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = kPalette[series_.size() % 8]; series_.push_back(ns); }
void add_series(const std::string& name, const xframe::OHLCVSeries& s, Srgb color) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = color; series_.push_back(ns); }
void clear_series() { series_.clear(); view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and append it as a named series. Returns false and appends nothing
// on error; `error` explains why.
bool add_series_csv(const std::string& path, const std::string& name, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
add_series(name, s);
return true;
}
int series_count() { return (int)series_.size(); }
int item_count() { size_t n = 0; for (auto& s : series_) n = std::max(n, s.data.size()); return (int)n; }
std::vector<double> closes_of(int i) { return xframe::series_closes(series_[i].data); }
@@ -77,6 +77,15 @@ add_series("SYM-A", xframe::make_seeded_series(60, 42));
void add_series(const std::string& name, const xframe::OHLCVSeries& s) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = kPalette[series_.size() % 8]; series_.push_back(ns); }
void add_series(const std::string& name, const xframe::OHLCVSeries& s, Srgb color) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = color; series_.push_back(ns); }
void clear_series() { series_.clear(); view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and append it as a named series. Returns false and appends nothing
// on error; `error` explains why.
bool add_series_csv(const std::string& path, const std::string& name, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
add_series(name, s);
return true;
}
int series_count() { return (int)series_.size(); }
int item_count() { size_t n = 0; for (auto& s : series_) n = std::max(n, s.data.size()); return (int)n; }
std::vector<double> closes_of(int i) { return xframe::series_closes(series_[i].data); }
@@ -115,6 +115,17 @@ public:
double get_brick_size() { return brick_size_; }
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; rebuild_bricks(); }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
const xframe::OHLCVSeries& series() const { return series_; }
int item_count() { return (int)bricks_.size(); }
void set_y_range(double lo, double hi) { auto_y_ = false; y_min_ = lo; y_max_ = hi; }
@@ -75,6 +75,15 @@ add_series("SYM-A", xframe::make_seeded_series(60, 42));
void add_series(const std::string& name, const xframe::OHLCVSeries& s) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = kPalette[series_.size() % 8]; series_.push_back(ns); }
void add_series(const std::string& name, const xframe::OHLCVSeries& s, Srgb color) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = color; series_.push_back(ns); }
void clear_series() { series_.clear(); view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and append it as a named series. Returns false and appends nothing
// on error; `error` explains why.
bool add_series_csv(const std::string& path, const std::string& name, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
add_series(name, s);
return true;
}
int series_count() { return (int)series_.size(); }
int item_count() { size_t n = 0; for (auto& s : series_) n = std::max(n, s.data.size()); return (int)n; }
std::vector<double> closes_of(int i) { return xframe::series_closes(series_[i].data); }
@@ -79,6 +79,15 @@ add_series("SYM-A", xframe::make_seeded_series(60, 42));
void add_series(const std::string& name, const xframe::OHLCVSeries& s) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = kPalette[series_.size() % 8]; series_.push_back(ns); }
void add_series(const std::string& name, const xframe::OHLCVSeries& s, Srgb color) { NamedSeries ns; ns.name = name; ns.data = s; ns.color = color; series_.push_back(ns); }
void clear_series() { series_.clear(); view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and append it as a named series. Returns false and appends nothing
// on error; `error` explains why.
bool add_series_csv(const std::string& path, const std::string& name, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
add_series(name, s);
return true;
}
int series_count() { return (int)series_.size(); }
int item_count() { size_t n = 0; for (auto& s : series_) n = std::max(n, s.data.size()); return (int)n; }
std::vector<double> closes_of(int i) { return xframe::series_closes(series_[i].data); }
+11
View File
@@ -78,6 +78,17 @@ set_series(xframe::make_seeded_series(60, 42));
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
void set_symbol(const std::string& s) { symbol_ = s; }
std::string symbol() { return symbol_; }
int series_count() { return series_.empty() ? 0 : 1; }
@@ -84,6 +84,17 @@ set_series(xframe::make_seeded_series(60, 42));
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
void set_symbol(const std::string& s) { symbol_ = s; }
std::string symbol() { return symbol_; }
int series_count() { return series_.empty() ? 0 : 1; }
@@ -78,6 +78,17 @@ set_series(xframe::make_seeded_series(60, 42));
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
void set_symbol(const std::string& s) { symbol_ = s; }
std::string symbol() { return symbol_; }
int series_count() { return series_.empty() ? 0 : 1; }
@@ -78,6 +78,17 @@ set_series(xframe::make_seeded_series(60, 42));
SStyle style() { return styles_->resolve(style_name_); }
void set_series(const xframe::OHLCVSeries& s) { series_ = s; view_first_ = 0.0; view_count_ = 0.0; }
// CSV: load an OHLCV file (format: see load_ohlcv_csv in StockData.h)
// and replace the series. Returns false and leaves the series
// unchanged on error; `error` explains why.
bool load_csv(const std::string& path, std::string& error) {
xframe::OHLCVSeries s = xframe::load_ohlcv_csv(path, error);
if (!error.empty()) return false;
set_series(s);
return true;
}
// Clear the chart: same as set_series with an empty series.
void clear_series() { set_series(xframe::OHLCVSeries{}); }
void set_symbol(const std::string& s) { symbol_ = s; }
std::string symbol() { return symbol_; }
int series_count() { return series_.empty() ? 0 : 1; }
+100
View File
@@ -0,0 +1,100 @@
// Unit test for xframe::load_ohlcv_csv / parse_ohlcv_csv_text (StockData.h).
// Compile: g++ -std=c++17 -Wall -Wextra -I widgets/components csv_unit_test.cpp -o /tmp/csv_unit_test
#include "StockData.h"
#include <cstdio>
#include <string>
static int failures = 0;
#define CHECK(cond, msg) do { \
if (!(cond)) { std::printf("FAIL: %s\n", msg); ++failures; } \
} while (0)
int main() {
std::string err;
int skipped = -1;
// 1. The 30-row sample fixture (header, YYYY-MM-DD dates).
auto s = xframe::load_ohlcv_csv("tests/data/ohlcv_sample.csv", err, &skipped);
CHECK(err.empty(), "sample: unexpected error");
CHECK(s.size() == 30, "sample: expected 30 rows");
CHECK(s.size() == 30 && s[0].timestamp == 1793577600LL, "sample: first date 2026-11-02 UTC");
CHECK(s.size() == 30 && s[0].close == 150.60, "sample: first close 150.60");
CHECK(s.size() == 30 && s[29].close == 152.25, "sample: last close 152.25");
CHECK(skipped == 0, "sample: no rows skipped");
bool sane = true;
for (auto& b : s)
if (!(b.high >= std::max(b.open, b.close) && b.low <= std::min(b.open, b.close) && b.volume > 0)) sane = false;
CHECK(sane, "sample: high/low/volume sane");
// 2. Second fixture differs (multi-series B symbol).
auto sb = xframe::load_ohlcv_csv("tests/data/ohlcv_sample_b.csv", err);
CHECK(err.empty() && sb.size() == 30, "sample_b: 30 rows");
CHECK(sb.size() == 30 && sb[29].close == 311.07, "sample_b: last close 311.07");
// 3. Massive aggregates format (header-matched, window_start ns).
auto m = xframe::load_ohlcv_csv("tests/data/SPY_fake.csv", err, &skipped);
CHECK(err.empty(), "massive: unexpected error");
CHECK(!m.empty(), "massive: rows loaded");
CHECK(!m.empty() && m[0].open == 660.00 && m[0].close == 659.49, "massive: first bar OHLC");
CHECK(!m.empty() && m[0].volume == 17171, "massive: first bar volume");
CHECK(!m.empty() && m[0].timestamp == 1794493800LL, "massive: window_start ns -> s");
CHECK(skipped == 0, "massive: no rows skipped");
// 4. Headerless 6-column positional.
auto h6 = xframe::parse_ohlcv_csv_text(
"2026-01-05,100.0,101.5,99.5,101.0,5000\n2026-01-06,101.0,102.0,100.5,101.8,6000\n", err);
CHECK(err.empty() && h6.size() == 2, "headerless6: 2 rows");
CHECK(h6.size() == 2 && h6[1].timestamp == 1767657600LL, "headerless6: second date 2026-01-06");
// 5. Headerless 5-column (no date): sequential daily timestamps from 2026-01-01.
auto h5 = xframe::parse_ohlcv_csv_text("100.0,101.5,99.5,101.0,5000\n101.0,102.0,100.5,101.8,6000\n", err);
CHECK(err.empty() && h5.size() == 2, "headerless5: 2 rows");
CHECK(h5.size() == 2 && h5[0].timestamp == 1767225600LL && h5[1].timestamp == 1767312000LL,
"headerless5: sequential dates from 2026-01-01");
// 6. Reordered header + extra columns ignored + volume missing.
auto rh = xframe::parse_ohlcv_csv_text(
"ticker,close,low,open,high\nACME,105.0,99.0,100.0,106.0\n", err);
CHECK(err.empty() && rh.size() == 1, "reordered: 1 row");
CHECK(rh.size() == 1 && rh[0].open == 100.0 && rh[0].close == 105.0 && rh[0].volume == 0,
"reordered: values by name, volume defaults 0");
// 7. Date formats: slash date, ISO datetime, epoch ms, epoch s.
auto df = xframe::parse_ohlcv_csv_text(
"date,open,high,low,close,volume\n"
"2026/01/05,100,101,99,100.5,10\n"
"2026-01-06T09:30:00Z,100,101,99,100.5,10\n"
"1767657600000,100,101,99,100.5,10\n"
"1767744000,100,101,99,100.5,10\n", err);
CHECK(err.empty() && df.size() == 4, "dates: 4 rows");
CHECK(df.size() == 4 && df[0].timestamp == 1767571200LL, "dates: slash date");
CHECK(df.size() == 4 && df[1].timestamp == 1767691800LL, "dates: ISO datetime 09:30");
CHECK(df.size() == 4 && df[2].timestamp == 1767657600LL, "dates: epoch ms");
CHECK(df.size() == 4 && df[3].timestamp == 1767744000LL, "dates: epoch s");
// 8. Malformed rows skipped and counted; CRLF + BOM + quoted field tolerated.
auto bad = xframe::parse_ohlcv_csv_text(
"\xEF\xBB\xBF""date,open,high,low,close,volume\r\n"
"2026-01-05,100,101,99,100.5,10\r\n"
"2026-01-06,not-a-number,101,99,100.5,10\r\n"
"2026-01-07,100,101\r\n"
"\"2026-01-08\",100,101,99,100.5,10\r\n", err, &skipped);
CHECK(err.empty() && bad.size() == 2, "malformed: 2 valid rows");
CHECK(skipped == 2, "malformed: 2 rows skipped");
CHECK(bad.size() == 2 && bad[1].timestamp == 1767830400LL, "malformed: quoted date row kept");
// 9. Errors: missing file, empty text, header missing close, no valid rows.
auto nf = xframe::load_ohlcv_csv("tests/data/does-not-exist.csv", err);
CHECK(!err.empty() && nf.empty(), "missing file: error set, empty series");
auto em = xframe::parse_ohlcv_csv_text("", err);
CHECK(!err.empty() && em.empty(), "empty text: error set");
auto mc = xframe::parse_ohlcv_csv_text("date,open,high,low\n2026-01-05,100,101,99\n", err);
CHECK(!err.empty() && mc.empty(), "missing close column: error set");
auto nv = xframe::parse_ohlcv_csv_text("date,open,high,low,close,volume\njunk,junk,junk,junk,junk,junk\n", err);
CHECK(!err.empty() && nv.empty(), "no valid rows: error set");
if (failures == 0) std::printf("csv_unit_test: ALL PASS\n");
else std::printf("csv_unit_test: %d FAILURES\n", failures);
return failures == 0 ? 0 : 1;
}
+358
View File
@@ -0,0 +1,358 @@
#!/usr/bin/env python3
"""Stock chart CSV test driver: proves every in-scope Stock* chart widget
plots real CSV data (not just the seeded template series).
- Compiles + runs widgets/tests/csv_unit_test.cpp (parser unit tests).
- For each of the 23 in-scope widgets: screenshots the template-data demo,
then a harness that loads tests/data/ohlcv_sample.csv (30 real OHLCV
rows) via the widget's load_csv()/add_series_csv() and screenshots it.
The two screenshots must differ substantially (CSV data visibly plots),
the CSV shot must be non-blank, and the widget must report 30 items.
- Also checks the failure path: a missing CSV file leaves the series
untouched and the harness exits 2.
- Multi-series widgets load ohlcv_sample.csv as "AAA" and
ohlcv_sample_b.csv as "BBB" after clear_series().
- Xvfb is restarted automatically if it dies mid-run (other jobs on this
server share it; a dead display is retried once per widget).
Re-derives every count from fresh artifacts each round; exits non-zero on
any failure. Attribution: XFrame.
"""
import os, re, subprocess, sys, time
from PIL import Image, ImageChops
WIDGETS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REPO = os.path.dirname(WIDGETS_DIR)
COMP = os.path.join(WIDGETS_DIR, "components")
TMP = "/tmp/stock-csv-shots"
BUILD = "/tmp/stock-csv-build"
CSV_A = os.path.join(REPO, "tests/data/ohlcv_sample.csv")
CSV_B = os.path.join(REPO, "tests/data/ohlcv_sample_b.csv")
DISPLAY = ":93"
ENV = dict(os.environ, DISPLAY=DISPLAY)
SINGLE = ["StockAccumulationDistribution", "StockAreaChart",
"StockBaselineChart", "StockCandlestickChart", "StockHeikinAshi",
"StockHollowCandles", "StockLineChart", "StockMoneyFlowChart",
"StockOBVChart", "StockOHLCBarChart", "StockRenko", "StockVWAP",
"StockVolumeBars", "StockVolumeCandles", "StockVolumeProfile"]
MULTI = ["StockCorrelationView", "StockIndexedComparison",
"StockMultiSymbolChart", "StockOverlayChart", "StockRatioChart",
"StockRelativePerformance", "StockSectorComparison",
"StockSpreadChart"]
WIDGETS = SINGLE + MULTI
os.makedirs(TMP, exist_ok=True)
os.makedirs(BUILD, exist_ok=True)
failures = []
rows = []
def run(*a, timeout=30, **k):
return subprocess.run(*a, capture_output=True, text=True, timeout=timeout,
env=ENV, **k)
def check(cond, msg):
if not cond:
failures.append(msg)
return cond
def nonbg(path):
im = Image.open(path).convert("L")
h = im.histogram()
modal = max(range(256), key=lambda v: h[v])
return sum(c for v, c in enumerate(h) if abs(v - modal) > 10)
def diff(a, b):
ia = Image.open(a).convert("RGB")
ib = Image.open(b).convert("RGB")
if ia.size != ib.size:
ib = ib.resize(ia.size)
return sum(ImageChops.difference(ia, ib).convert("L").histogram()[31:])
def shot(wid, path):
r = run(["import", "-window", str(wid), path], timeout=15)
return os.path.exists(path) and os.path.getsize(path) > 0
# --- Xvfb management (display can die mid-run; restart on demand) ---
_xvfb = None
def xvfb_alive():
r = subprocess.run(["xdpyinfo", "-display", DISPLAY],
capture_output=True, timeout=5)
return r.returncode == 0
def restart_xvfb():
global _xvfb
if _xvfb is not None:
try:
_xvfb.terminate()
_xvfb.wait(timeout=5)
except Exception:
try:
_xvfb.kill()
except Exception:
pass
_xvfb = None
subprocess.run(["pkill", "-f", f"Xvfb {DISPLAY}"], capture_output=True,
timeout=10)
time.sleep(0.5)
try:
os.remove(f"/tmp/.X{DISPLAY[1:]}-lock")
except FileNotFoundError:
pass
_xvfb = subprocess.Popen(["Xvfb", DISPLAY, "-screen", "0", "1024x768x24"])
for _ in range(20):
if xvfb_alive():
return True
time.sleep(0.25)
return False
def ensure_xvfb():
if not xvfb_alive():
return restart_xvfb()
return True
def wait_window(name, proc, tries=50):
for _ in range(tries):
if proc.poll() is not None:
return None
rr = run(["xdotool", "search", "--name", f"{name} - XFrame demo"],
timeout=10)
if rr.stdout.strip():
return rr.stdout.strip().split()[0]
time.sleep(0.2)
return None
def make_harness(name):
"""Build a harness main from the widget's own demo main: same window,
but the series comes from the CSV file(s) given on argv."""
src = open(os.path.join(COMP, name, f"main_{name}.cpp")).read()
src = src.replace("int main()\n{", "int main(int argc, char** argv)\n{\n (void)argc;", 1)
if "#include <string>" not in src:
src = src.replace(f'#include "{name}.h"',
f'#include "{name}.h"\n#include <string>', 1)
m = re.search(r"^.*\bwidget\(display, screen, window, gc, &styles,.*\);$",
src, re.M)
assert m, f"{name}: construction line not found"
if name in SINGLE:
snippet = ('\n { std::string csv_err; '
'if (!widget.load_csv(argv[1], csv_err)) { '
'std::fprintf(stderr, "csv: %s\\n", csv_err.c_str()); return 2; } }'
'\n std::printf("csv_rows=%d\\n", widget.item_count());')
else:
snippet = ('\n { std::string csv_err; widget.clear_series(); '
'if (!widget.add_series_csv(argv[1], "AAA", csv_err)) return 2; '
'if (!widget.add_series_csv(argv[2], "BBB", csv_err)) return 2; }'
'\n std::printf("csv_rows=%d\\n", widget.item_count());')
src = src[:m.end()] + snippet + src[m.end():]
out = os.path.join(TMP, f"harness_{name}.cpp")
open(out, "w").write(src)
return out
# --- send_delete helper ---
sd = "/tmp/send_delete"
if not os.path.exists(sd):
subprocess.run(["cc", os.path.join(REPO, "widgets", "test-driver",
"send_delete.c"), "-lX11", "-o", sd],
capture_output=True, timeout=60)
def shoot_demo(binp, name, outpng, args, tag):
"""Run a demo binary, screenshot its window, exit it cleanly.
Returns (ok, note, stdout_text)."""
logout = open(os.path.join(TMP, f"{name}_{tag}.stdout"), "w")
logf = open(os.path.join(TMP, f"{name}_{tag}.stderr"), "wb")
p = subprocess.Popen([binp] + args, env=ENV, stdout=logout, stderr=logf)
wid = wait_window(name, p)
if wid is None:
rc = p.poll()
try:
p.wait(timeout=3)
except Exception:
p.kill()
p.wait(timeout=5)
logf.close(); logout.close()
return False, f"{tag}: no window rc={rc}", ""
time.sleep(0.4)
ok = shot(wid, outpng)
if p.poll() is None:
run([sd, str(wid)], timeout=10)
try:
p.wait(timeout=5)
except Exception:
p.kill(); p.wait(timeout=5)
logf.close(); logout.close()
if not ok:
return False, f"{tag}: screenshot failed", ""
return True, "", open(os.path.join(TMP, f"{name}_{tag}.stdout")).read()
# --- 0. parser unit test ---
unit_src = os.path.join(WIDGETS_DIR, "tests", "csv_unit_test.cpp")
unit_bin = os.path.join(TMP, "csv_unit_test")
r = subprocess.run(["g++", "-std=c++17", "-Wall", "-Wextra", "-I", COMP,
unit_src, "-o", unit_bin],
capture_output=True, text=True, timeout=120)
check(r.returncode == 0 and "warning:" not in r.stderr,
f"csv_unit_test compile failed/warnings: {r.stderr[:400]}")
if r.returncode == 0:
r2 = subprocess.run([unit_bin], capture_output=True, text=True,
timeout=30, cwd=REPO)
check(r2.returncode == 0, f"csv_unit_test rc={r2.returncode}: {r2.stdout}")
print("csv_unit_test:", r2.stdout.strip().splitlines()[-1]
if r2.stdout else "no output", flush=True)
if not restart_xvfb():
print("FATAL: Xvfb never answered", flush=True)
sys.exit(1)
try:
for name in WIDGETS:
row = {"name": name, "build": "FAIL", "draw": "FAIL",
"csv_diff": "FAIL", "rows": "FAIL", "badpath": "FAIL",
"notes": ""}
notes = []
# Build the template demo via cmake (isolated build dir).
bdir = os.path.join(BUILD, name)
r = subprocess.run(["cmake", "-S", os.path.join(COMP, name), "-B", bdir,
"-DCMAKE_CXX_FLAGS=-Wall -Wextra"],
capture_output=True, text=True, timeout=120)
out = r.stdout + r.stderr
r2 = subprocess.run(["cmake", "--build", bdir], capture_output=True,
text=True, timeout=180) if r.returncode == 0 else None
out2 = (r2.stdout + r2.stderr) if r2 else ""
binp = os.path.join(bdir, name)
if r.returncode != 0 or (r2 and r2.returncode != 0):
notes.append(f"template build failed: {(out + out2)[-300:]}")
row["notes"] = "; ".join(notes); rows.append(row)
failures.append(f"{name}: template build failed"); continue
if "warning:" in out2:
notes.append("template build warnings")
failures.append(f"{name}: warnings in template build")
# Build the CSV harness with g++ directly.
hsrc = make_harness(name)
hbin = os.path.join(TMP, f"harness_{name}")
r3 = subprocess.run(["g++", "-std=c++17", "-O2", "-Wall", "-Wextra",
"-I", os.path.join(COMP, name), "-I", COMP,
hsrc, "-lX11", "-o", hbin],
capture_output=True, text=True, timeout=120)
if r3.returncode != 0 or "warning:" in r3.stderr:
notes.append(f"harness build failed/warnings: {r3.stderr[-300:]}")
row["notes"] = "; ".join(notes); rows.append(row)
failures.append(f"{name}: harness build failed"); continue
if not (os.path.exists(binp) and os.access(binp, os.X_OK)):
notes.append("template binary missing"); row["notes"] = "; ".join(notes)
rows.append(row); failures.append(f"{name}: binary missing"); continue
row["build"] = "PASS"
# Template screenshot (retry once after an X restart).
tmpl = os.path.join(TMP, name + "_template.png")
ok, note, _ = shoot_demo(binp, name, tmpl, [], "template")
if not ok:
ensure_xvfb()
ok, note, _ = shoot_demo(binp, name, tmpl, [], "template")
if not ok:
notes.append(note)
failures.append(f"{name}: {note}")
row["notes"] = "; ".join(notes); rows.append(row); continue
# CSV harness: bad path must exit 2 without a window.
rb = subprocess.run([hbin, "/tmp/does-not-exist.csv", CSV_B],
capture_output=True, text=True, timeout=20, env=ENV)
if rb.returncode == 2:
row["badpath"] = "PASS"
else:
notes.append(f"bad path rc={rb.returncode} (want 2)")
failures.append(f"{name}: bad path rc={rb.returncode}")
# CSV harness screenshot (retry once after an X restart).
csvshot = os.path.join(TMP, name + "_csv.png")
ok, note, csv_out = shoot_demo(hbin, name, csvshot,
[CSV_A, CSV_B], "csv")
if not ok:
ensure_xvfb()
ok, note, csv_out = shoot_demo(hbin, name, csvshot,
[CSV_A, CSV_B], "csv")
if not ok:
notes.append(note)
failures.append(f"{name}: {note}")
row["notes"] = "; ".join(notes); rows.append(row); continue
nb = nonbg(csvshot)
if nb > 20:
row["draw"] = "PASS"
else:
notes.append(f"csv draw blank: {nb} non-bg px")
failures.append(f"{name}: csv draw blank")
d = diff(tmpl, csvshot)
# Calibrated threshold: the two runs differ ONLY in the series, so
# any diff far above rendering noise proves the CSV drives the
# plot. Clean-tree re-renders are pixel-identical (visreg baseline
# 0.0000%) and the OHLC driver treats a hover diff > 50 as a real
# response; thin-line widgets (OBV, VWAP, overlays) score in the
# low thousands while filled candle/bar charts score far higher.
# 1000 is 20x the hover threshold and far above noise.
if d > 1000:
row["csv_diff"] = "PASS"
else:
notes.append(f"csv vs template diff too small: {d}")
failures.append(f"{name}: csv diff {d} <= 1000")
m = re.search(r"csv_rows=(\d+)", csv_out)
# StockRenko counts bricks, not bars: 30 CSV bars build 25 bricks
# at the default brick size, so it expects 1..30, not exactly 30.
if name == "StockRenko":
rows_ok = bool(m) and 0 < int(m.group(1)) <= 30
want = "1..30"
else:
rows_ok = bool(m) and int(m.group(1)) == 30
want = "30"
if rows_ok:
row["rows"] = "PASS"
else:
notes.append(f"csv_rows={m.group(1) if m else 'missing'} (want {want})")
failures.append(f"{name}: csv_rows != {want}")
row["notes"] = "; ".join(notes)
rows.append(row)
print(f"{name}: build={row['build']} draw={row['draw']} "
f"csv_diff={row['csv_diff']} rows={row['rows']} "
f"badpath={row['badpath']}" +
(f" [{row['notes']}]" if row["notes"] else ""), flush=True)
finally:
if _xvfb is not None:
try:
_xvfb.terminate()
_xvfb.wait(timeout=5)
except Exception:
try:
_xvfb.kill()
except Exception:
pass
try:
os.remove(f"/tmp/.X{DISPLAY[1:]}-lock")
except FileNotFoundError:
pass
with open(os.path.join(TMP, "results.csv"), "w") as f:
f.write("widget,build,draw,csv_diff,rows,badpath,notes\n")
for r in rows:
f.write(",".join([r["name"], r["build"], r["draw"], r["csv_diff"],
r["rows"], r["badpath"],
'"' + r["notes"].replace('"', '""') + '"']) + "\n")
npass = sum(1 for r in rows if all(r[c] == "PASS" for c in
("build", "draw", "csv_diff", "rows", "badpath")))
print(f"CSV group: {npass}/{len(WIDGETS)} widgets fully PASS; "
f"failures={len(failures)}")
for f in failures:
print("FAIL:", f)
sys.exit(0 if not failures and npass == len(WIDGETS) else 1)