Ind* indicators: OHLCV CSV loading for all 250 kinds

Reuse the stock-chart CSV parser (same format, same sample file):
IndicatorWidget::populate_from_csv / Widget::load_csv_data replace
the demo bars and the lines recompute from the loaded series at draw
time, so no per-kind wiring was needed. Adds csv::bars_from_rows +
date_to_epoch_nanos (Bar::time is nanoseconds; this also makes the
four pivot widgets compute real lines instead of all-NaN). Demo
series stays as fallback (reset_to_demo, loaded_from_csv flag).

Tests: 9 new (all-250 load + recompute + headless draw, pivot fix,
bad-CSV keeps demo bars); full workspace suite clean except the
pre-existing lightgui-gen fixture failure. Screenshots: 250/250
CSV-loaded renders under Xvfb differ from demo goldens (RMSE
0.0060-0.0661). Docs: docs/indicators-csv.md; rustdoc Ind* pages
updated.
This commit is contained in:
Muse committed 2026-12-02 10:44:12 +00:00
1 parent d507697ae8
commit 2819a316e4
6 files changed
+662 -2

No files matched your search

+15
View File
@@ -2593,6 +2593,18 @@ impl IndicatorWidget {
pub fn new_widget(name: &str, kind: &str, x: i32, y: i32, w: i32, h: i32) -> IndicatorWidget {
IndicatorWidget::new(name, kind, x, y, w, h)
}
/// Load OHLCV CSV text into this indicator — see
/// `crate::indicators::IndicatorWidget::populate_from_csv`.
/// Returns the number of rows loaded.
pub fn populate_from_csv(&mut self, text: &str) -> Result<usize, String> {
self.inner.populate_from_csv(text)
}
/// Drop loaded bars and go back to the built-in demo series.
pub fn reset_to_demo(&mut self) {
self.inner.reset_to_demo();
}
}
archetype_impl!(IndicatorWidget, Archetype::Indicator,
@@ -2607,6 +2619,9 @@ archetype_impl!(IndicatorWidget, Archetype::Indicator,
}
self.inner.draw(target, styles);
}
fn load_csv_data(&mut self, csv: &str) -> Result<usize, String> {
self.populate_from_csv(csv)
}
fn on_button_press(&mut self, x: i32, y: i32, button: u32) -> bool {
if self.inner.on_button_press(x, y, button) {
self.on_click();
+175 -1
View File
@@ -1,4 +1,5 @@
//! OHLCV CSV loading for the stock chart widgets (`XGraph` / `ChartWidget`).
//! OHLCV CSV loading for the stock chart widgets (`XGraph` / `ChartWidget`)
//! and the `Ind*` indicator widgets (`IndicatorWidget`).
//!
//! # CSV format
//!
@@ -32,6 +33,7 @@
//! Renko, ...) are computed from the loaded rows, never fetched.
use crate::graph::{PlotView, XGraphBar};
use xframe_indicators::Bar;
/// One OHLCV row: the `date` label plus the four prices and volume.
#[derive(Debug, Clone, PartialEq)]
@@ -136,6 +138,117 @@ pub fn parse_ohlcv_csv(text: &str) -> Result<Vec<OhlcvRow>, String> {
Ok(rows)
}
/// Days since 1970-01-01 for a proleptic Gregorian date (Howard
/// Hinnant's `days_from_civil`). No chrono dependency.
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400; // [0, 399]
let mp = (m + 9) % 12; // Mar=0 .. Feb=11
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146097 + doe - 719468
}
fn days_in_month(y: i64, m: i64) -> i64 {
match m {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 {
29
} else {
28
}
}
_ => 0,
}
}
/// Convert a CSV `date` field (the shapes `parse_ohlcv_csv` accepts) to
/// nanoseconds since the Unix epoch — the unit of
/// `xframe_indicators::Bar::time`. A bare date means midnight UTC; a
/// trailing time (`HH:MM:SS`, space- or `T`-separated) is added.
/// Returns `None` when the field is not a recognisable date.
pub fn date_to_epoch_nanos(date: &str) -> Option<i64> {
const DAY_NANOS: i64 = 86_400_000_000_000;
let s = date.trim();
if s.is_empty() {
return None;
}
// All digits: YYYYMMDD (8) or epoch seconds (9+).
if s.chars().all(|c| c.is_ascii_digit()) {
if s.len() == 8 {
let y: i64 = s[0..4].parse().ok()?;
let m: i64 = s[4..6].parse().ok()?;
let d: i64 = s[6..8].parse().ok()?;
if d > days_in_month(y, m) {
return None;
}
return Some(days_from_civil(y, m, d) * DAY_NANOS);
}
if s.len() >= 9 {
let secs: i64 = s.parse().ok()?;
return secs.checked_mul(1_000_000_000);
}
return None;
}
let b = s.as_bytes();
if b.len() < 10 {
return None;
}
let date_ok = b[0..4].iter().all(|c| c.is_ascii_digit())
&& (b[4] == b'-' || b[4] == b'/')
&& b[5..7].iter().all(|c| c.is_ascii_digit())
&& (b[7] == b'-' || b[7] == b'/')
&& b[8..10].iter().all(|c| c.is_ascii_digit());
if !date_ok {
return None;
}
let y: i64 = s[0..4].parse().ok()?;
let m: i64 = s[5..7].parse().ok()?;
let d: i64 = s[8..10].parse().ok()?;
if d > days_in_month(y, m) {
return None;
}
let mut nanos = days_from_civil(y, m, d) * DAY_NANOS;
// Optional trailing time: " HH:MM:SS" or "THH:MM:SS".
if b.len() > 10 {
if b[10] != b' ' && b[10] != b'T' {
return None;
}
let parts: Vec<&str> = s[11..].split(':').collect();
if parts.len() != 3 {
return None;
}
let hh: i64 = parts[0].parse().ok()?;
let mm: i64 = parts[1].parse().ok()?;
let ss: i64 = parts[2].parse().ok()?;
if hh > 23 || mm > 59 || ss > 60 {
return None;
}
nanos += (hh * 3600 + mm * 60 + ss) * 1_000_000_000;
}
Some(nanos)
}
/// Convert parsed OHLCV rows to `xframe_indicators::Bar`s — the series
/// an `Ind*` indicator computes from. `time` is the row date as
/// nanoseconds since the epoch (`Bar::time`'s unit). Rows whose date
/// cannot be converted (impossible after `parse_ohlcv_csv`, which
/// validates dates) fall back to consecutive days from 2026-01-01, so
/// day-grouped indicators (pivot points) still see one bar per day.
pub fn bars_from_rows(rows: &[OhlcvRow]) -> Vec<Bar> {
rows.iter()
.enumerate()
.map(|(i, r)| {
let time = date_to_epoch_nanos(&r.date)
.unwrap_or(1_767_225_600_000_000_000 + i as i64 * 86_400_000_000_000);
Bar::new(r.open, r.high, r.low, r.close, r.volume, time)
})
.collect()
}
/// Close prices, in row order.
pub fn closes(rows: &[OhlcvRow]) -> Vec<f64> {
rows.iter().map(|r| r.close).collect()
@@ -310,3 +423,64 @@ pub fn volume_profile(rows: &[OhlcvRow], bins: usize) -> (Vec<f64>, Vec<String>)
.collect();
(vols, labels)
}
#[cfg(test)]
mod csv_tests {
use super::*;
#[test]
fn date_to_epoch_nanos_known_dates() {
// 2026-01-01 00:00:00 UTC = 1767225600 s (demo_bars' day0).
assert_eq!(
date_to_epoch_nanos("2026-01-01"),
Some(1_767_225_600_000_000_000)
);
assert_eq!(
date_to_epoch_nanos("2026-01-05"),
Some(1_767_571_200_000_000_000)
);
assert_eq!(
date_to_epoch_nanos("2026/01/05"),
Some(1_767_571_200_000_000_000)
);
assert_eq!(
date_to_epoch_nanos("20260105"),
Some(1_767_571_200_000_000_000)
);
assert_eq!(
date_to_epoch_nanos("1767571200"),
Some(1_767_571_200_000_000_000)
);
assert_eq!(
date_to_epoch_nanos("2026-01-05 06:30:00"),
Some(1_767_571_200_000_000_000 + 23_400_000_000_000)
);
assert_eq!(
date_to_epoch_nanos("2026-01-05T06:30:00"),
Some(1_767_571_200_000_000_000 + 23_400_000_000_000)
);
assert_eq!(date_to_epoch_nanos("2026-02-29"), None); // not a leap year
assert_eq!(
date_to_epoch_nanos("2024-02-29"),
Some(1_709_164_800_000_000_000)
);
assert_eq!(date_to_epoch_nanos("not-a-date"), None);
assert_eq!(date_to_epoch_nanos(""), None);
}
#[test]
fn bars_from_rows_maps_dates_and_prices() {
let rows = parse_ohlcv_csv(
"date,open,high,low,close,volume\n\
2026-01-05,100.00,101.20,99.10,100.80,850000\n\
2026-01-06,100.80,102.00,100.10,101.50,900000\n",
)
.unwrap();
let bars = bars_from_rows(&rows);
assert_eq!(bars.len(), 2);
assert_eq!(bars[0].time, 1_767_571_200_000_000_000);
assert_eq!(bars[1].time, 1_767_657_600_000_000_000);
assert!((bars[0].close - 100.80).abs() < 1e-9);
assert!((bars[1].volume - 900000.0).abs() < 1e-9);
}
}
+286
View File
@@ -178,6 +178,10 @@ pub struct IndicatorWidget {
/// Registry line index for multi-line defs (e.g. Donchian Upper=0).
pub line: Option<usize>,
pub bars: Vec<Bar>,
/// Whether the current bars came from a CSV load
/// (`populate_from_csv` / `load_csv_data`) rather than the built-in
/// demo series. Cleared by `set_bars` and `reset_to_demo`.
pub loaded_from_csv: bool,
pub view: PlotView,
/// Chart background / grid / candle colours (were hardcoded in `draw`).
pub background_color: Srgb,
@@ -212,6 +216,7 @@ impl IndicatorWidget {
indicator,
line: None,
bars: demo_bars(demo_bar_count(name)),
loaded_from_csv: false,
background_color: Srgb::new(255, 255, 255),
grid_color: Srgb::new(225, 225, 225),
candle_up_color,
@@ -244,9 +249,60 @@ impl IndicatorWidget {
pub fn set_bars(&mut self, bars: Vec<Bar>) {
self.bars = bars;
self.loaded_from_csv = false;
self.view.reset(self.bars.len());
}
/// The bars this widget currently computes from (the demo series
/// until a CSV is loaded).
pub fn bars(&self) -> &[Bar] {
&self.bars
}
/// Whether the current bars came from a CSV load
/// (`populate_from_csv` / `load_csv_data`) rather than the built-in
/// demo series.
pub fn loaded_from_csv(&self) -> bool {
self.loaded_from_csv
}
/// Load OHLCV CSV text (`csv::parse_ohlcv_csv` format:
/// `date,open,high,low,close[,volume]`) and recompute this
/// indicator's lines from the loaded bars. Every `Ind*` kind loads
/// the same way: the lines are recomputed from `self.bars` at draw
/// time (`lines()`), so no per-kind wiring is needed — the def's
/// `compute` runs over whatever bars are current. Returns the
/// number of rows loaded. A failed load leaves the previous bars
/// (demo or earlier CSV) untouched. The view resets to show the
/// loaded series from the first bar.
pub fn populate_from_csv(&mut self, text: &str) -> Result<usize, String> {
let rows = crate::csv::parse_ohlcv_csv(text)?;
let n = rows.len();
let bars = crate::csv::bars_from_rows(&rows);
self.set_bars(bars);
self.loaded_from_csv = true;
Ok(n)
}
/// Alias for `populate_from_csv`, matching the
/// `Widget::load_csv_data` name the demo binary and embedders call.
pub fn load_csv_data(&mut self, text: &str) -> Result<usize, String> {
self.populate_from_csv(text)
}
/// Drop loaded bars and go back to the built-in demo series
/// (`demo_bars`, 120 or 250 bars per widget, as the C++ mains used).
pub fn reset_to_demo(&mut self) {
let n = demo_bar_count(&self.state.name);
self.set_bars(demo_bars(n));
}
/// The indicator lines for the current bars, recomputed on every
/// call — the same values `draw` plots.
pub fn computed_lines(&self) -> Lines {
self.lines()
}
/// Background colour (default white, as before).
pub fn get_background_color(&self) -> Srgb {
self.background_color
@@ -699,6 +755,9 @@ impl IndicatorWidget {
mod indicator_tests {
use super::*;
/// The repo's 30-row sample (weekday bars, 2026-01-05..2026-02-13).
const SAMPLE_CSV: &str = include_str!("../../xframe-demo/examples/data/sample-ohlcv.csv");
#[test]
fn demo_series_matches_cpp_stockdata() {
// First bars of C++ make_seeded_series(250, 42), recomputed
@@ -755,4 +814,231 @@ mod indicator_tests {
assert_eq!(w3.bars.len(), 250);
assert_eq!(w3.view.count, 200.0);
}
#[test]
fn csv_load_recomputes_lines_from_loaded_bars() {
let mut w = IndicatorWidget::new("IndSMA", "SMA", 0, 0, 200, 90);
assert_eq!(w.bars.len(), 120);
assert!(!w.loaded_from_csv());
let demo_lines = w.computed_lines();
let n = w.populate_from_csv(SAMPLE_CSV).expect("sample CSV loads");
assert_eq!(n, 30);
assert_eq!(w.bars.len(), 30);
assert!(w.loaded_from_csv());
assert!((w.bars[0].close - 100.01).abs() < 1e-9);
assert_eq!(w.bars[0].time, 1_767_571_200_000_000_000);
let loaded_lines = w.computed_lines();
assert_eq!(loaded_lines.len(), demo_lines.len());
assert!(!loaded_lines.is_empty());
for s in &loaded_lines {
assert_eq!(s.len(), 30);
}
// The recomputed values differ from the demo ones (same window
// length, different data): compare the last N finite demo values
// against the loaded finite values.
let demo_finite: Vec<f64> = demo_lines
.iter()
.flatten()
.filter(|v| v.is_finite())
.copied()
.collect();
let loaded_finite: Vec<f64> = loaded_lines
.iter()
.flatten()
.filter(|v| v.is_finite())
.copied()
.collect();
assert!(!loaded_finite.is_empty());
let n = loaded_finite.len();
assert_ne!(loaded_finite, demo_finite[demo_finite.len() - n..].to_vec());
// View reset to the loaded series.
assert_eq!(w.view_first(), 0.0);
}
#[test]
fn csv_load_failure_keeps_demo_bars() {
let mut w = IndicatorWidget::new("IndRSI", "RSI", 0, 0, 200, 90);
let before = w.bars.clone();
let err = w
.populate_from_csv("date,open,high,low,close,volume\nnot-a-date,1,2,3,4,5\n")
.unwrap_err();
assert!(err.contains("line 2"), "{err}");
assert_eq!(w.bars, before);
assert!(!w.loaded_from_csv());
assert!(w.populate_from_csv("").is_err());
assert_eq!(w.bars, before);
}
#[test]
fn csv_load_all_250_kinds() {
// 30-row sample file: every kind must load and recompute without
// crashing; def kinds must return lines.
let mut checked = 0;
let mut with_finite_30 = 0;
let mut with_def = 0;
let mut no_finite_30: Vec<&str> = Vec::new();
for e in crate::registry::REGISTRY
.iter()
.filter(|e| e.family == "Ind")
{
let mut w = IndicatorWidget::new(e.name, e.kind, 0, 0, 200, 90);
let n = w
.populate_from_csv(SAMPLE_CSV)
.unwrap_or_else(|err| panic!("{}: CSV load failed: {err}", e.name));
assert_eq!(n, 30, "{}", e.name);
assert_eq!(w.bars.len(), 30, "{}", e.name);
assert!(w.loaded_from_csv(), "{}", e.name);
let lines = w.computed_lines();
if w.indicator.is_some() {
with_def += 1;
assert!(!lines.is_empty(), "{}: def kind with no lines", e.name);
for s in &lines {
assert!(s.len() <= 30, "{}: line longer than bars", e.name);
}
}
// The 50 no-def kinds return no lines at all (see the
// module docs), so they can never have a finite value.
if lines.iter().flatten().any(|v| v.is_finite()) {
with_finite_30 += 1;
} else {
no_finite_30.push(e.name);
}
checked += 1;
}
assert_eq!(checked, 250);
assert_eq!(with_def, 200, "expected 200 def kinds, got {with_def}");
// 30 bars is shorter than many indicators' warmups (e.g. 50-bar
// spans), so some def kinds legitimately return all-NaN here
// (measured: 189 of 200 def kinds finite); the 250-bar load
// below is the real check. The floor only guards against a mass
// regression.
assert!(
with_finite_30 >= 180,
"only {with_finite_30}/200 def kinds produced a finite value from 30 bars: {no_finite_30:?}"
);
// 250-row CSV (the demo series, epoch dates): warmups are met,
// so every def kind should produce at least one finite value.
let mut long_csv = String::from(
"date,open,high,low,close,volume
",
);
for (i, b) in demo_bars(250).iter().enumerate() {
long_csv.push_str(&format!(
"{},{:.6},{:.6},{:.6},{:.6},{:.1}
",
1767225600 + i as i64 * 86400,
b.open,
b.high,
b.low,
b.close,
b.volume
));
}
let mut with_finite_250 = 0;
let mut no_finite_250: Vec<&str> = Vec::new();
for e in crate::registry::REGISTRY
.iter()
.filter(|e| e.family == "Ind")
{
let mut w = IndicatorWidget::new(e.name, e.kind, 0, 0, 200, 90);
let n = w.populate_from_csv(&long_csv).unwrap();
assert_eq!(n, 250, "{}", e.name);
let lines = w.computed_lines();
if lines.iter().flatten().any(|v| v.is_finite()) {
with_finite_250 += 1;
} else {
// The only kinds allowed to stay all-NaN on 250 bars are
// the no-def ones (no lines at all); a def kind with no
// finite value is a real bug.
assert!(
w.indicator.is_none(),
"{}: def kind produced no finite value from 250 bars",
e.name
);
no_finite_250.push(e.name);
}
}
assert_eq!(
with_finite_250, with_def,
"only {with_finite_250}/{with_def} def kinds produced a finite value from 250 bars"
);
assert_eq!(
no_finite_250.len(),
250 - with_def,
"unexpected all-NaN kinds: {no_finite_250:?}"
);
}
#[test]
fn csv_loaded_indicators_draw_headlessly() {
use xframe_core::{Canvas, StyleManager};
let mut canvas = Canvas::new(200, 90);
let mut styles = StyleManager::new();
let mut drawn = 0;
for e in crate::registry::REGISTRY
.iter()
.filter(|e| e.family == "Ind")
{
let mut w = IndicatorWidget::new(e.name, e.kind, 0, 0, 200, 90);
w.populate_from_csv(SAMPLE_CSV).unwrap();
canvas.clear(0x202020);
w.draw(&mut canvas, &mut styles);
// Every indicator draws at least a background + grid, so the
// canvas must differ from the clear colour.
assert!(
canvas.data().iter().any(|&p| p != 0x202020),
"{}: draw left a blank canvas",
e.name
);
drawn += 1;
}
assert_eq!(drawn, 250);
}
#[test]
fn csv_load_gives_pivot_indicators_real_lines() {
// `f_pivots` groups bars by `Bar::time` in days (nanoseconds).
// The demo series stores seconds in `time`, so every demo bar
// lands on day 0 and the pivot lines are all NaN; CSV-loaded
// bars carry real nanosecond dates, so the pivots compute.
let mut w = IndicatorWidget::new(
"IndStandardPivotPoints",
"Pivot Points Standard",
0,
0,
200,
90,
);
let demo_lines = w.computed_lines();
assert!(!demo_lines.is_empty(), "pivot kind should have a def");
assert!(
demo_lines.iter().flatten().all(|v| !v.is_finite()),
"demo pivots should be all-NaN (day-0 time quirk)"
);
w.populate_from_csv(SAMPLE_CSV).unwrap();
let lines = w.computed_lines();
assert!(
lines.iter().flatten().any(|v| v.is_finite()),
"loaded pivots should have finite values"
);
}
#[test]
fn reset_to_demo_restores_demo_bars() {
let mut w = IndicatorWidget::new("IndSMA", "SMA", 0, 0, 200, 90);
w.populate_from_csv(SAMPLE_CSV).unwrap();
assert!(w.loaded_from_csv());
w.reset_to_demo();
assert!(!w.loaded_from_csv());
assert_eq!(w.bars.len(), 120);
assert_eq!(w.bars, demo_bars(120));
}
#[test]
fn widget_trait_load_csv_data_reaches_indicators() {
let mut w = crate::create("IndSMA").expect("IndSMA exists");
let n = w.load_csv_data(SAMPLE_CSV).expect("load via Widget trait");
assert_eq!(n, 30);
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ pub use archetypes::{
IndicatorWidget, InstrumentWidget, LabelWidget, ListSelWidget, RangeWidget, ToggleWidget,
};
pub use graph::{GraphSeries, PlotView, SeriesKind, XGraph, XGraphBar};
pub use csv::{parse_ohlcv_csv, OhlcvRow};
pub use csv::{bars_from_rows, date_to_epoch_nanos, parse_ohlcv_csv, OhlcvRow};
pub use registry::{by_family, by_section, count_by_archetype, create, find, names, RegistryEntry, REGISTRY};
pub use spreadsheet::{Cell, XSpreadsheet};
pub use state::{button, Key, Rect, WidgetState};
+181
View File
@@ -0,0 +1,181 @@
# Ind* indicator widgets: how series data gets in (Rust)
How the 250 `Ind*` widgets in `lightgui_rust` ingest data, what sample
data ships with them (a built-in demo series — see below), and how to
replace it with your own CSV. The reference implementation is
`crates/xframe-widgets/src/indicators.rs` (`IndicatorWidget`) plus the
shared CSV parser in `crates/xframe-widgets/src/csv.rs`
(`parse_ohlcv_csv`, `bars_from_rows`, `date_to_epoch_nanos`). The CSV
format is the same one the stock chart widgets use — see
`docs/stock-charts-csv.md` for the full format reference.
## The short version
```rust
use xframe_widgets::{create, Widget};
let mut ind = create("IndSMA").unwrap();
ind.set_bounds(40, 40, 720, 520);
let csv = std::fs::read_to_string(
"crates/xframe-demo/examples/data/sample-ohlcv.csv",
).unwrap();
let rows = ind.load_csv_data(&csv).expect("sample CSV loads");
assert_eq!(rows, 30); // 30 bars; the SMA line recomputes from them
```
Or from the shell, with a live window under Xvfb:
```sh
cargo run -p xframe-demo -- IndSMA \
--csv crates/xframe-demo/examples/data/sample-ohlcv.csv \
--geometry 20,20,760,560 --hold 5
```
## Audit: how data gets in
All 250 `Ind*` kinds are one archetype, `IndicatorWidget`
(`crates/xframe-widgets/src/archetypes.rs`), wrapping the inner
`indicators::IndicatorWidget`. There are not 250 structs: the `kind`
string (e.g. `"SMA"`) specialises the archetype, and the `fdi`
definition for that kind (`xframe_indicators::find_def`) supplies the
computation.
### Why no per-kind wiring was needed
Each indicator recomputes its lines from its current bars on every
draw (`IndicatorWidget::lines()` calls `ind.compute(&self.bars)`), so
loading a series is one generic operation: replace `self.bars` and the
next draw plots the new lines. The CSV job therefore adds a single
loader on the archetype instead of 250 setters. The 50 kinds with no
`fdi` def are unaffected in the same way: they draw from the same bars
(grid + view, or candles), so a loaded series changes what they draw
too — just with no indicator lines on top.
### The 250 kinds, by what they plot
| Group | Count | What a loaded series changes |
| --- | --- | --- |
| Pane defs | 128 | The indicator's own lines/bars in its pane (own y-scale, candles hidden) |
| Overlay defs | 69 | Indicator lines drawn over the loaded price candles |
| Markers defs | 3 | Marker triangles at the computed points, over the candles |
| No `fdi` def | 50 | No lines — 38 draw grid + view only, 12 draw the loaded candles (`NO_DEF_CANDLES`) |
Line style is `Lines` for 193 def kinds and `Bars` for 7. Thirty defs
are shared by more than one widget (e.g. `RSI` backs six widgets:
`IndRSI`, `IndAdaptiveRSI`, `IndCutlerRSI`, `IndEhlersSmoothedRSI`,
`IndMACDofRSI`, `IndRSX`), so the same computation with different
defaults/line selections appears under several names.
### Data model
`IndicatorWidget` holds `bars: Vec<xframe_indicators::Bar>` — one
`{open, high, low, close, volume, time}` per row — plus a `PlotView`
(first/count window, auto-y, wheel zoom, drag pan, crosshair) and the
per-widget candle palette surveyed from the C++ headers. `Bar::time`
is nanoseconds since the epoch (the C++ `long long`).
## The API
| Method | What it does |
| --- | --- |
| `populate_from_csv(text)` / `load_csv_data(text)` | Parse OHLCV CSV (`csv::parse_ohlcv_csv` format) and recompute from the loaded bars. Returns the number of rows loaded. A failed load leaves the previous bars untouched. The view resets to the first bar. |
| `set_bars(bars)` | Replace the series directly with `Vec<Bar>` (clears the loaded-from-CSV flag). |
| `reset_to_demo()` | Drop loaded bars and restore the built-in demo series. |
| `bars()` | The bars currently computed from. |
| `loaded_from_csv()` | Whether the current bars came from a CSV load. |
| `computed_lines()` | The indicator lines for the current bars — the same values `draw` plots. |
| `set_param(i, v)` / `get_param(i)` | Indicator parameters by index (def kinds only), e.g. the SMA period. Changing a parameter recomputes the lines on the next draw, from whichever bars are loaded. |
The generic entry point is `Widget::load_csv_data` (overridden on the
`IndicatorWidget` archetype to call `populate_from_csv`), so the demo
binary's `--csv` flag and any embedder that talks to widgets through
the trait get CSV loading for indicators with no extra code.
## Template data: the demo series
A fresh indicator renders without any loading: it starts on the
built-in deterministic demo series, `demo_bars(n)` — a port of C++
`xframe::make_seeded_series(n, 42)` (`widgets/components/StockData.h`,
lightgui eb0b5fc), dated 2026-01-01 + `i` days. 85 widgets use 120
bars, the rest 250 (`BARS_120`, surveyed from the C++ mains). The demo
series is the fallback, not the data: `loaded_from_csv()` is false
until a CSV load succeeds, and `reset_to_demo()` restores it.
## CSV format
Exactly the stock-chart format (`csv::parse_ohlcv_csv` — same parser,
same rules, no second format):
```text
date,open,high,low,close,volume
2026-01-05,100.00,101.20,99.10,100.80,850000
```
One bar per line, comma-separated, in that column order. A header row
is optional (the first line is skipped when its second field is not a
number). `volume` is optional and defaults to `0.0`. Blank lines and
lines starting with `#` are skipped. `date` must look like a date:
`YYYY-MM-DD`, `YYYY/MM/DD`, `YYYYMMDD`, epoch seconds (all digits,
9+), or a date followed by a time (`YYYY-MM-DD HH:MM:SS`). A bad row
is an error naming its line number, and the whole load fails — the
previous bars stay in place.
Dates become `Bar::time` in nanoseconds via
`csv::date_to_epoch_nanos` (a bare date means midnight UTC; a trailing
time is added). The repo's sample file is
`crates/xframe-demo/examples/data/sample-ohlcv.csv` (30 weekday bars,
2026-01-05..2026-02-13).
### The pivot quirk (why loaded data fixes pivot points)
`Bar::time` is documented as nanoseconds, but the demo series stores
*seconds* in it (`demo_bars` passes `1767225600 + i * 86400`). The
pivot-point defs group bars into days with
`time / 86_400_000_000_000`, so every demo bar lands on day 0 and the
four pivot widgets (`IndStandardPivotPoints`,
`IndCamarillaPivotPoints`, `IndFibonacciPivotPoints`,
`IndWoodiePivotPoints`) draw all-NaN lines from demo data. CSV-loaded
bars carry real nanosecond dates, so the pivots compute — loading data
is the fix, not a workaround. `demo_bars` itself is untouched: changing
it would move the demo screenshots for all 250 widgets.
## How much data is enough
Indicator warmups vary: a 20-period SMA needs 20 bars, a 52-bar span
needs 52. Measured with the sample file and a 250-row CSV built from
the demo series:
- 30 rows (sample file): 189 of the 200 def kinds produce at least one
finite line value; the other 11 need longer warmups.
- 250 rows: all 200 def kinds produce finite values.
- The 50 no-def kinds never produce lines (by design — they have no
def to compute), at any length.
A short file is not an error: the widget loads, draws what it can, and
the lines fill in as more bars arrive. If you need a specific
indicator's full warmup, load at least its longest period (e.g. 52
bars for the Ichimoku spans).
## Verification
- Unit/parser tests in `crates/xframe-widgets/src/csv.rs`
(`date_to_epoch_nanos` known dates incl. leap years, `bars_from_rows`
mapping) and `src/indicators.rs` (sample load recomputes lines, bad
CSV keeps demo bars, all-250 load + recompute + headless draw,
pivots go from all-NaN to finite, reset-to-demo, `Widget` trait
path): 16 tests in `xframe-widgets --lib`, all passing.
- Screenshots under Xvfb (`xframe-demo --csv`, 800x600, settle-capture
as in `tools/visreg/run.sh`): 20 kinds sampled across Overlay /
Pane / Markers / no-def / pivots — every CSV shot differs from its
demo-data shot (normalised RMSE 0.021–0.065, vs the 0.005 visreg
threshold), proving loaded data changes the plotted output. Full
250-kind CSV sweep under Xvfb: all 250 kinds render with the sample
loaded, all 800x600, and every CSV shot differs from its demo-data
golden (normalised RMSE min 0.0060, median 0.0345, max 0.0661 — none
below the 0.005 visreg threshold; the smallest movers are the no-def
pane kinds, whose grid scale alone shifts, and the largest are the
pivot points, which go from blank to drawn).
- Full workspace suite: no regressions (the only failures are
pre-existing: `lightgui-gen` fixtures on pristine HEAD, and
`lightgui-support` font/theme suites, which need a display and pass
under Xvfb).
+4
View File
@@ -301,3 +301,7 @@ let obv = obv_line(&rows);
sample file.
* Doc blog: <https://rustdoc.lightgui.com/> — each widget page has a
"Plotting your own data (CSV)" section.
* `docs/indicators-csv.md` — the same CSV format, loaded into the 250
`Ind*` indicator widgets (`IndicatorWidget::populate_from_csv` /
`Widget::load_csv_data`): the indicator lines recompute from the
loaded bars, with the built-in demo series as fallback.