Files
lightgui_rust/crates/xframe-widgets/src/csv.rs
Muse 2819a316e4 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.
2026-12-02 10:44:12 +00:00

487 lines
16 KiB
Rust

//! OHLCV CSV loading for the stock chart widgets (`XGraph` / `ChartWidget`)
//! and the `Ind*` indicator widgets (`IndicatorWidget`).
//!
//! # CSV format
//!
//! One bar per line, comma-separated, in this column order:
//!
//! ```text
//! date,open,high,low,close,volume
//! 2026-01-05,100.00,101.20,99.10,100.80,850000
//! ```
//!
//! * A header row is optional: the first non-blank line is skipped when
//! its second field is not a number (so `date,open,high,low,close,volume`
//! is recognised as a header, and a file without one just works).
//! * `volume` is optional and defaults to `0.0` when the column is absent.
//! Columns after `volume` are ignored.
//! * Blank lines and lines starting with `#` are skipped. Surrounding
//! whitespace and surrounding double quotes on a field are stripped.
//! * `date` is kept verbatim as the chart's x-axis label. It 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`). Anything else is an error naming the line.
//! * The four prices must parse as finite numbers. A bad row is an error
//! naming its line number — the whole load fails, nothing is plotted
//! half-way (callers clear-then-load, so a failed load leaves the
//! previous data in place only if they loaded into a fresh chart; see
//! `XGraph::load_ohlcv_csv`).
//!
//! No network, no live market data: the repo's sample file is
//! `crates/xframe-demo/examples/data/sample-ohlcv.csv` (30 weekday bars,
//! 2026-01-05..2026-02-13). Derived series below (VWAP, OBV, Heikin-Ashi,
//! 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)]
pub struct OhlcvRow {
/// Date label, kept verbatim (also used as the x-axis label).
pub date: String,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
/// 0.0 when the CSV has no volume column.
pub volume: f64,
}
/// Does `s` look like a date (see the module docs)?
fn looks_like_date(s: &str) -> bool {
if s.is_empty() {
return false;
}
if s.chars().all(|c| c.is_ascii_digit()) {
// YYYYMMDD, or epoch seconds (9+ digits).
return s.len() == 8 || s.len() >= 9;
}
let b = s.as_bytes();
if b.len() < 10 {
return false;
}
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 false;
}
// Anything after the date must be a time separator (space or 'T').
b.len() == 10 || b[10] == b' ' || b[10] == b'T'
}
/// Parse OHLCV CSV text into rows. See the module docs for the format;
/// errors name the offending line number.
pub fn parse_ohlcv_csv(text: &str) -> Result<Vec<OhlcvRow>, String> {
let mut rows: Vec<OhlcvRow> = Vec::new();
let mut seen_row = false;
for (idx, raw) in text.lines().enumerate() {
let line_no = idx + 1;
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let fields: Vec<&str> = line
.split(',')
.map(|f| f.trim().trim_matches('"'))
.collect();
if !seen_row {
seen_row = true;
// Header row: the open field is not a number.
if fields.len() < 2 || fields[1].parse::<f64>().is_err() {
continue;
}
}
if fields.len() < 5 {
return Err(format!(
"line {}: expected at least 5 columns (date,open,high,low,close), got {}",
line_no,
fields.len()
));
}
let date = fields[0];
if !looks_like_date(date) {
return Err(format!(
"line {}: bad date {:?} (expected YYYY-MM-DD, YYYY/MM/DD, YYYYMMDD, or epoch seconds)",
line_no, date
));
}
let num = |i: usize| -> Result<f64, String> {
match fields[i].parse::<f64>() {
Ok(v) if v.is_finite() => Ok(v),
_ => Err(format!(
"line {}: {:?} is not a finite number",
line_no, fields[i]
)),
}
};
let open = num(1)?;
let high = num(2)?;
let low = num(3)?;
let close = num(4)?;
let volume = if fields.len() >= 6 { num(5)? } else { 0.0 };
rows.push(OhlcvRow {
date: date.to_string(),
open,
high,
low,
close,
volume,
});
}
if rows.is_empty() {
return Err("no data rows (empty file, or header only)".to_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()
}
/// Volumes, in row order.
pub fn volumes(rows: &[OhlcvRow]) -> Vec<f64> {
rows.iter().map(|r| r.volume).collect()
}
/// Heikin-Ashi bars: `ha_close = (o+h+l+c)/4`,
/// `ha_open = (prev_ha_open + prev_ha_close)/2` (first bar: the raw open),
/// `ha_high = max(h, ha_open, ha_close)`, `ha_low = min(l, ha_open, ha_close)`.
pub fn heikin_ashi_bars(rows: &[OhlcvRow]) -> Vec<XGraphBar> {
let mut out = Vec::with_capacity(rows.len());
let mut prev_open = 0.0;
let mut prev_close = 0.0;
for (i, r) in rows.iter().enumerate() {
let ha_close = (r.open + r.high + r.low + r.close) / 4.0;
let ha_open = if i == 0 {
r.open
} else {
(prev_open + prev_close) / 2.0
};
let ha_high = r.high.max(ha_open).max(ha_close);
let ha_low = r.low.min(ha_open).min(ha_close);
out.push(XGraphBar::new(ha_open, ha_high, ha_low, ha_close));
prev_open = ha_open;
prev_close = ha_close;
}
out
}
/// Fixed-brick Renko bars from the close series. The anchor starts at the
/// first close; each time the close moves one `brick` past the anchor a
/// brick is emitted (up: open=anchor, close=anchor+brick; down: the
/// mirror) and the anchor steps by `brick`. Returns no bricks for an
/// empty series or a non-positive brick; capped at 50,000 bricks so a
/// pathological brick size cannot blow up memory.
pub fn renko_bars(rows: &[OhlcvRow], brick: f64) -> Vec<XGraphBar> {
let mut out = Vec::new();
if rows.is_empty() || !brick.is_finite() || brick <= 0.0 {
return out;
}
let mut anchor = rows[0].close;
for r in rows {
while r.close >= anchor + brick && out.len() < 50_000 {
out.push(XGraphBar::new(
anchor,
anchor + brick,
anchor,
anchor + brick,
));
anchor += brick;
}
while r.close <= anchor - brick && out.len() < 50_000 {
out.push(XGraphBar::new(
anchor,
anchor,
anchor - brick,
anchor - brick,
));
anchor -= brick;
}
}
out
}
/// VWAP line: cumulative `typical * volume / cumulative volume`, with
/// `typical = (high + low + close) / 3`. Bars with zero volume fall back
/// to the typical price, so an all-zero-volume file still yields a line.
pub fn vwap_line(rows: &[OhlcvRow]) -> Vec<f64> {
let mut out = Vec::with_capacity(rows.len());
let mut cum_pv = 0.0;
let mut cum_v = 0.0;
for r in rows {
let typical = (r.high + r.low + r.close) / 3.0;
cum_pv += typical * r.volume;
cum_v += r.volume;
out.push(if cum_v > 0.0 { cum_pv / cum_v } else { typical });
}
out
}
/// On-Balance Volume: starts at the first bar's volume, then adds the
/// bar's volume when the close rose, subtracts it when the close fell,
/// unchanged on a flat close.
pub fn obv_line(rows: &[OhlcvRow]) -> Vec<f64> {
let mut out = Vec::with_capacity(rows.len());
let mut obv = 0.0;
for (i, r) in rows.iter().enumerate() {
if i == 0 {
obv = r.volume;
} else {
let prev = rows[i - 1].close;
if r.close > prev {
obv += r.volume;
} else if r.close < prev {
obv -= r.volume;
}
}
out.push(obv);
}
out
}
/// Chaikin money-flow multiplier for one bar: `((c-l)-(h-c))/(h-l)`,
/// 0 when `high == low`.
fn money_flow_multiplier(r: &OhlcvRow) -> f64 {
if r.high != r.low {
((r.close - r.low) - (r.high - r.close)) / (r.high - r.low)
} else {
0.0
}
}
/// Accumulation/Distribution line: the cumulative sum of
/// `multiplier * volume` per bar.
pub fn accum_dist_line(rows: &[OhlcvRow]) -> Vec<f64> {
let mut out = Vec::with_capacity(rows.len());
let mut ad = 0.0;
for r in rows {
ad += money_flow_multiplier(r) * r.volume;
out.push(ad);
}
out
}
/// Per-bar money flow (`multiplier * volume`, not cumulative — that is
/// what `accum_dist_line` is).
pub fn money_flow_line(rows: &[OhlcvRow]) -> Vec<f64> {
rows.iter()
.map(|r| money_flow_multiplier(r) * r.volume)
.collect()
}
/// Volume profile: the rows' volume bucketed by typical price into `bins`
/// bins (clamped to 1..=50) spanning `[min low, max high]`. Returns the
/// per-bin volumes and `"lo-hi"` labels for the x axis.
pub fn volume_profile(rows: &[OhlcvRow], bins: usize) -> (Vec<f64>, Vec<String>) {
let bins = bins.clamp(1, 50);
if rows.is_empty() {
return (Vec::new(), Vec::new());
}
let lo = rows.iter().map(|r| r.low).fold(f64::INFINITY, f64::min);
let hi = rows
.iter()
.map(|r| r.high)
.fold(f64::NEG_INFINITY, f64::max);
let mut vols = vec![0.0; bins];
let width = (hi - lo) / bins as f64;
for r in rows {
let typical = (r.high + r.low + r.close) / 3.0;
let mut b = if width > 0.0 {
((typical - lo) / width) as usize
} else {
0
};
if b >= bins {
b = bins - 1;
}
vols[b] += r.volume;
}
let labels = (0..bins)
.map(|i| {
format!(
"{}-{}",
PlotView::fmt(lo + i as f64 * width),
PlotView::fmt(lo + (i + 1) as f64 * width)
)
})
.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);
}
}