Stock charts: OHLCV CSV loading for all 23 data-plotting kinds
- New csv.rs: parse_ohlcv_csv (date,open,high,low,close[,volume], header optional, errors name the line) + derived series (VWAP, OBV, accumulation/distribution, money flow, Heikin-Ashi, Renko, volume profile). - XGraph: load_*_csv loaders (candles, OHLC bars, close line, indexed closes, VWAP over candles, OBV, A/D, money flow, Heikin-Ashi, Renko, volume bars/candles/profile), add_ohlc_csv + add_ratio_line / add_spread_line for two-symbol compare, clear_data, SeriesKind::Bars (volume bars from the zero line; y range forced to contain 0). - ChartWidget::populate_from_csv picks the series per kind; the 14 drawing/annotation kinds reject CSV with an error. Widget trait gains load_csv_data (default: rejects); XGraph loads candles. - xframe-demo: run_widget_with_csv + --csv flag; csv-chart-shots example renders all 23 kinds headlessly and diffs vs the blank template; 30-row sample CSV in examples/data/. - docs/stock-charts-csv.md: audit (no template data ships inside the widget), CSV spec, per-kind table, worked examples, limits. Also corrects the stale gen.rs comment about a seeded preview series. - 13 new tests in csv_tests.rs (parser, derived math, per-kind population, clear/populate, ratio/spread, headless renders).
This commit is contained in:
1 parent
414cfe2a54
commit
84348fd378
13 files changed
+1522
-9
No files matched your search
@@ -24,3 +24,8 @@ cargo build # must be warning-free (the C++ build was zero-warning)
|
||||
```
|
||||
|
||||
Rust 1.100.1 stable, GTK 3.24 (gtk-rs 0.18), serde/serde_json 1.0.
|
||||
|
||||
## Docs
|
||||
|
||||
- `docs/stock-charts-csv.md` — how the stock chart widgets ingest
|
||||
plotting data (CSV format, per-kind series, clear/populate, limits).
|
||||
@@ -2345,10 +2345,14 @@ fn emit_widget_props(o: &mut String, w: &Widget, m: &XFrameMap, var: &str, kind:
|
||||
));
|
||||
}
|
||||
} else if t == "StockChart" {
|
||||
// StockCandlestickChart draws its seeded preview series; the old
|
||||
// GTK chart's CSV/indicator/drawing engine has no counterpart in
|
||||
// the XFrame widget API, so the design data is recorded here for
|
||||
// hand-wiring instead of silently dropped.
|
||||
// A fresh StockCandlestickChart plots no data: XGraph starts with
|
||||
// an empty series list (there is no seeded preview series in the
|
||||
// Rust widget). Load OHLCV CSV text at runtime
|
||||
// (`ChartWidget::populate_from_csv` / `Widget::load_csv_data`,
|
||||
// see docs/stock-charts-csv.md). The old GTK chart's
|
||||
// CSV/indicator/drawing engine has no counterpart in the XFrame
|
||||
// widget API, so the design data is recorded here for hand-wiring
|
||||
// instead of silently dropped.
|
||||
// up/down colours are emitted by the generic Phase 4 loop below.
|
||||
if has("data-file")
|
||||
|| has("indicators")
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! csv-chart-shots — render every data-plotting stock chart kind with the
|
||||
//! sample OHLCV CSV and save a PNG per kind, plus the blank (no-data)
|
||||
//! template for comparison.
|
||||
//!
|
||||
//! Run it from the workspace root:
|
||||
//!
|
||||
//! cargo run -p xframe-demo --example csv-chart-shots -- [OUT_DIR] [CSV]
|
||||
//!
|
||||
//! Defaults: OUT_DIR `target/csv-shots`, CSV
|
||||
//! `crates/xframe-demo/examples/data/sample-ohlcv.csv`. Prints one line
|
||||
//! per kind: rows loaded, series plotted, and how many pixels differ
|
||||
//! from the same widget rendered with no data (the template) — a
|
||||
//! populated chart must differ by thousands of pixels, a blank one by
|
||||
//! zero. PNGs are written via PPM + `convert` (ImageMagick), the same
|
||||
//! route `xframe-test-runner` uses.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use xframe_core::{Canvas, StyleManager};
|
||||
use xframe_widgets::create;
|
||||
|
||||
const KINDS: &[&str] = &[
|
||||
"StockAccumulationDistribution",
|
||||
"StockAreaChart",
|
||||
"StockBaselineChart",
|
||||
"StockCandlestickChart",
|
||||
"StockCorrelationView",
|
||||
"StockHeikinAshi",
|
||||
"StockHollowCandles",
|
||||
"StockIndexedComparison",
|
||||
"StockLineChart",
|
||||
"StockMoneyFlowChart",
|
||||
"StockMultiSymbolChart",
|
||||
"StockOBVChart",
|
||||
"StockOHLCBarChart",
|
||||
"StockOverlayChart",
|
||||
"StockRatioChart",
|
||||
"StockRelativePerformance",
|
||||
"StockRenko",
|
||||
"StockSectorComparison",
|
||||
"StockSpreadChart",
|
||||
"StockVWAP",
|
||||
"StockVolumeBars",
|
||||
"StockVolumeCandles",
|
||||
"StockVolumeProfile",
|
||||
];
|
||||
|
||||
const W: i32 = 760;
|
||||
const H: i32 = 560;
|
||||
|
||||
fn render(name: &str, csv: Option<&str>) -> Result<(Vec<u32>, usize), String> {
|
||||
let mut w = create(name).ok_or_else(|| format!("no widget {}", name))?;
|
||||
w.set_bounds(0, 0, W, H);
|
||||
let mut rows = 0;
|
||||
if let Some(text) = csv {
|
||||
rows = w.load_csv_data(text).map_err(|e| format!("{}: {}", name, e))?;
|
||||
}
|
||||
let mut canvas = Canvas::new(W, H);
|
||||
let mut styles = StyleManager::new();
|
||||
w.draw(&mut canvas, &mut styles);
|
||||
Ok((canvas.data().to_vec(), rows))
|
||||
}
|
||||
|
||||
fn write_png(pixels: &[u32], out: &Path) -> Result<(), String> {
|
||||
let ppm = out.with_extension("ppm");
|
||||
let mut f = std::fs::File::create(&ppm).map_err(|e| e.to_string())?;
|
||||
writeln!(f, "P6\n{} {}\n255", W, H).map_err(|e| e.to_string())?;
|
||||
let mut rgb = Vec::with_capacity(pixels.len() * 3);
|
||||
for p in pixels {
|
||||
rgb.push(((p >> 16) & 0xff) as u8);
|
||||
rgb.push(((p >> 8) & 0xff) as u8);
|
||||
rgb.push((p & 0xff) as u8);
|
||||
}
|
||||
f.write_all(&rgb).map_err(|e| e.to_string())?;
|
||||
drop(f);
|
||||
let ok = std::process::Command::new("convert")
|
||||
.arg(&ppm)
|
||||
.arg(out)
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false);
|
||||
let _ = std::fs::remove_file(&ppm);
|
||||
if ok {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("convert (ImageMagick) failed".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<i32, Box<dyn std::error::Error>> {
|
||||
let argv: Vec<String> = std::env::args().collect();
|
||||
let out_dir = PathBuf::from(argv.get(1).map(String::as_str).unwrap_or("target/csv-shots"));
|
||||
let csv_path = argv
|
||||
.get(2)
|
||||
.map(String::as_str)
|
||||
.unwrap_or("crates/xframe-demo/examples/data/sample-ohlcv.csv");
|
||||
let csv = std::fs::read_to_string(csv_path)
|
||||
.map_err(|e| format!("--csv {}: {}", csv_path, e))?;
|
||||
std::fs::create_dir_all(&out_dir)?;
|
||||
// Blank template (no data) for the comparison shot.
|
||||
let (blank, _) = render("StockCandlestickChart", None)?;
|
||||
write_png(&blank, &out_dir.join("blank-StockCandlestickChart.png"))?;
|
||||
println!("blank-StockCandlestickChart.png: 0 rows, template (no series)");
|
||||
let mut worst = usize::MAX;
|
||||
let mut worst_name = "";
|
||||
for name in KINDS {
|
||||
let (pixels, rows) = render(name, Some(&csv))?;
|
||||
let diff = pixels
|
||||
.iter()
|
||||
.zip(blank.iter())
|
||||
.filter(|(a, b)| a != b)
|
||||
.count();
|
||||
if diff < worst {
|
||||
worst = diff;
|
||||
worst_name = name;
|
||||
}
|
||||
write_png(&pixels, &out_dir.join(format!("{}.png", name)))?;
|
||||
println!("{}.png: {} rows, {} pixels differ from blank", name, rows, diff);
|
||||
}
|
||||
println!("least-different kind: {} ({} pixels)", worst_name, worst);
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(code) => ExitCode::from(code as u8),
|
||||
Err(e) => {
|
||||
eprintln!("csv-chart-shots: {}", e);
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
date,open,high,low,close,volume
|
||||
2026-01-05,100.00,100.02,99.61,100.01,573984
|
||||
2026-01-06,100.01,100.24,97.57,98.46,847806
|
||||
2026-01-07,98.46,99.02,97.81,98.93,1786666
|
||||
2026-01-08,98.93,99.29,97.76,97.76,744056
|
||||
2026-01-09,97.76,99.14,97.72,98.46,1278302
|
||||
2026-01-12,98.46,99.08,97.59,98.86,1476047
|
||||
2026-01-13,98.86,99.34,98.25,99.00,1791774
|
||||
2026-01-14,99.00,99.66,98.15,99.48,644258
|
||||
2026-01-15,99.48,99.93,99.35,99.77,1016476
|
||||
2026-01-16,99.77,99.92,98.50,98.59,1105410
|
||||
2026-01-19,98.59,98.62,97.43,98.19,1595023
|
||||
2026-01-20,98.19,98.95,97.86,98.19,1619090
|
||||
2026-01-21,98.19,98.34,97.30,98.02,1402059
|
||||
2026-01-22,98.02,100.66,97.87,100.11,669281
|
||||
2026-01-23,100.11,101.07,99.65,100.81,1167090
|
||||
2026-01-26,100.81,102.25,100.59,101.80,1631072
|
||||
2026-01-27,101.80,102.47,99.84,100.37,1566345
|
||||
2026-01-28,100.37,100.88,100.35,100.37,1022278
|
||||
2026-01-29,100.37,101.65,100.13,101.08,812617
|
||||
2026-01-30,101.08,102.55,101.06,101.68,1267058
|
||||
2026-02-02,101.68,102.21,101.17,101.95,974281
|
||||
2026-02-03,101.95,102.79,101.65,102.56,1295380
|
||||
2026-02-04,102.56,102.99,101.04,101.56,803595
|
||||
2026-02-05,101.56,102.08,101.28,101.97,1229454
|
||||
2026-02-06,101.97,103.22,101.27,102.57,1336492
|
||||
2026-02-09,102.57,102.87,101.43,102.18,1328594
|
||||
2026-02-10,102.18,103.25,101.75,102.64,1534124
|
||||
2026-02-11,102.64,102.83,101.91,102.76,1452702
|
||||
2026-02-12,102.76,102.99,102.20,102.85,1764979
|
||||
2026-02-13,102.85,103.38,102.49,102.99,1469966
|
||||
|
@@ -56,6 +56,22 @@ pub fn run_widget(
|
||||
dark: bool,
|
||||
hold: Option<u64>,
|
||||
geometry: Option<(i16, i16, u16, u16)>,
|
||||
) -> Result<i32, Box<dyn std::error::Error>> {
|
||||
run_widget_with_csv(name, dark, hold, geometry, None)
|
||||
}
|
||||
|
||||
/// Like [`run_widget`], but when `csv` holds OHLCV CSV text
|
||||
/// (`date,open,high,low,close[,volume]`) it is loaded into the widget
|
||||
/// first (`Widget::load_csv_data` — chart widgets plot it, other
|
||||
/// widgets report an error and the demo exits 2). This is how the stock
|
||||
/// chart widgets are shown with real data: see
|
||||
/// `docs/stock-charts-csv.md` and the `--csv` flag of the binary.
|
||||
pub fn run_widget_with_csv(
|
||||
name: &str,
|
||||
dark: bool,
|
||||
hold: Option<u64>,
|
||||
geometry: Option<(i16, i16, u16, u16)>,
|
||||
csv: Option<String>,
|
||||
) -> Result<i32, Box<dyn std::error::Error>> {
|
||||
let meta: &'static WidgetMeta = match registry::by_name(name) {
|
||||
Some(m) => m,
|
||||
@@ -95,6 +111,12 @@ pub fn run_widget(
|
||||
// default text (see the module docs of the binary).
|
||||
let kind = widget.kind().to_string();
|
||||
widget.set_text(&kind);
|
||||
if let Some(text) = &csv {
|
||||
if let Err(e) = widget.load_csv_data(text) {
|
||||
eprintln!("xframe-demo: --csv: {}", e);
|
||||
return Ok(2);
|
||||
}
|
||||
}
|
||||
|
||||
let ctx = DrawCtx::new(&x, win, gc, font);
|
||||
ctx.bind_font();
|
||||
|
||||
@@ -32,7 +32,7 @@ use std::process::ExitCode;
|
||||
use xframe_common::registry;
|
||||
|
||||
fn usage() -> &'static str {
|
||||
"usage: xframe-demo <WidgetName> [--dark] [--hold SECS] [--geometry X,Y,W,H] [--list]\n xframe-demo --list # print all 547 registry widget names"
|
||||
"usage: xframe-demo <WidgetName> [--dark] [--hold SECS] [--geometry X,Y,W,H] [--csv FILE] [--list]\n xframe-demo --list # print all 547 registry widget names"
|
||||
}
|
||||
|
||||
struct Args {
|
||||
@@ -41,6 +41,7 @@ struct Args {
|
||||
list: bool,
|
||||
hold: Option<u64>,
|
||||
geometry: Option<(i16, i16, u16, u16)>,
|
||||
csv: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_args(argv: &[String]) -> Result<Args, String> {
|
||||
@@ -50,6 +51,7 @@ fn parse_args(argv: &[String]) -> Result<Args, String> {
|
||||
list: false,
|
||||
hold: None,
|
||||
geometry: None,
|
||||
csv: None,
|
||||
};
|
||||
let mut i = 1;
|
||||
while i < argv.len() {
|
||||
@@ -64,6 +66,10 @@ fn parse_args(argv: &[String]) -> Result<Args, String> {
|
||||
.ok_or("--hold needs SECS")?,
|
||||
);
|
||||
}
|
||||
"--csv" => {
|
||||
i += 1;
|
||||
args.csv = Some(argv.get(i).ok_or("--csv needs a file path")?.to_string());
|
||||
}
|
||||
"--geometry" => {
|
||||
i += 1;
|
||||
let v = argv.get(i).ok_or("--geometry needs X,Y,W,H")?;
|
||||
@@ -116,7 +122,13 @@ fn run() -> Result<i32, Box<dyn std::error::Error>> {
|
||||
Some(n) => n.clone(),
|
||||
None => return Err(format!("no widget name\n{}", usage()).into()),
|
||||
};
|
||||
xframe_demo::run_widget(&name, args.dark, args.hold, args.geometry)
|
||||
let csv = match &args.csv {
|
||||
Some(path) => {
|
||||
Some(std::fs::read_to_string(path).map_err(|e| format!("--csv {}: {}", path, e))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
xframe_demo::run_widget_with_csv(&name, args.dark, args.hold, args.geometry, csv)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
|
||||
@@ -2357,6 +2357,52 @@ impl ChartWidget {
|
||||
pub fn get_overlay(&self) -> Option<&str> {
|
||||
self.overlay.as_deref()
|
||||
}
|
||||
|
||||
/// Load OHLCV CSV text into this chart, plotting the series this
|
||||
/// kind stands for — see `docs/stock-charts-csv.md` for the per-kind
|
||||
/// table. Candles for `CandlestickChart` / `HollowCandles`, plain
|
||||
/// OHLC bars for `OHLCBarChart`, Heikin-Ashi candles, Renko bricks
|
||||
/// (brick = 1% of the first close), the close line for the line
|
||||
/// kinds, closes indexed to 100 for the comparison kinds, candles
|
||||
/// plus the VWAP line for `VWAP`, the OBV / money-flow /
|
||||
/// accumulation-distribution lines, volume bars / volume candles /
|
||||
/// the 10-bin volume profile. Returns the number of CSV rows
|
||||
/// loaded. Drawing/annotation kinds (Arrow, Trendline, ...) plot no
|
||||
/// data series and return an error.
|
||||
pub fn populate_from_csv(&mut self, text: &str) -> Result<usize, String> {
|
||||
let name = self.state.name.clone();
|
||||
match self.kind.as_str() {
|
||||
"CandlestickChart" | "HollowCandles" => {
|
||||
self.graph.load_ohlcv_csv(&name, text, true)
|
||||
}
|
||||
"OHLCBarChart" => self.graph.load_ohlcv_csv(&name, text, false),
|
||||
"HeikinAshi" => self.graph.load_heikin_ashi_csv(&name, text),
|
||||
"Renko" => self.graph.load_renko_csv(&name, text, None),
|
||||
"LineChart" | "AreaChart" | "BaselineChart" | "CorrelationView"
|
||||
| "MultiSymbolChart" | "OverlayChart" | "RatioChart" | "SpreadChart" => {
|
||||
self.graph.load_close_line_csv(&name, text)
|
||||
}
|
||||
"IndexedComparison" | "RelativePerformance" | "SectorComparison" => {
|
||||
self.graph.load_indexed_close_csv(&name, text)
|
||||
}
|
||||
"VWAP" => self.graph.load_vwap_csv(&name, text),
|
||||
"OBVChart" => self.graph.load_obv_csv(&name, text),
|
||||
"MoneyFlowChart" => self.graph.load_money_flow_csv(&name, text),
|
||||
"AccumulationDistribution" => self.graph.load_accum_dist_csv(&name, text),
|
||||
"VolumeBars" => self.graph.load_volume_csv(&name, text),
|
||||
"VolumeCandles" => self.graph.load_volume_candles_csv(&name, text),
|
||||
"VolumeProfile" => self.graph.load_volume_profile_csv(&name, text, 10),
|
||||
_ => Err(format!(
|
||||
"{} is a drawing/annotation overlay: it plots no data series, so CSV data cannot be loaded into it. Position it with set_anchor(bar, price) instead.",
|
||||
self.state.name
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop every plotted series and every x label.
|
||||
pub fn clear_data(&mut self) {
|
||||
self.graph.clear_data();
|
||||
}
|
||||
}
|
||||
|
||||
archetype_impl!(ChartWidget, Archetype::Chart,
|
||||
@@ -2493,6 +2539,9 @@ archetype_impl!(ChartWidget, Archetype::Chart,
|
||||
self.graph.state.bounds = b;
|
||||
self.graph.view.bounds = b;
|
||||
}
|
||||
fn load_csv_data(&mut self, csv: &str) -> Result<usize, String> {
|
||||
self.populate_from_csv(csv)
|
||||
}
|
||||
fn draw(&self, target: &mut dyn DrawTarget, styles: &mut StyleManager) {
|
||||
if !self.state.visible {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
//! OHLCV CSV loading for the stock chart widgets (`XGraph` / `ChartWidget`).
|
||||
//!
|
||||
//! # 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};
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
@@ -43,6 +43,9 @@ pub enum SeriesKind {
|
||||
Line = 0,
|
||||
OhlcBars = 1,
|
||||
Candlesticks = 2,
|
||||
/// Vertical bars from the zero line (volume). Values live in `line`,
|
||||
/// like `Line` — see `GraphSeries::bar_series`.
|
||||
Bars = 3,
|
||||
}
|
||||
|
||||
/// One data series (C++ `XGraph::Series`).
|
||||
@@ -93,12 +96,30 @@ impl GraphSeries {
|
||||
}
|
||||
}
|
||||
|
||||
/// Volume-style series: vertical bars from the zero line, values in
|
||||
/// `line` (see `SeriesKind::Bars`).
|
||||
pub fn bar_series(name: &str, color: Srgb, values: Vec<f64>) -> GraphSeries {
|
||||
GraphSeries {
|
||||
name: name.to_string(),
|
||||
color,
|
||||
kind: SeriesKind::Bars,
|
||||
line: values,
|
||||
bars: Vec::new(),
|
||||
up_color: Srgb::new(0, 150, 0),
|
||||
down_color: Srgb::new(200, 30, 30),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
match self.kind {
|
||||
SeriesKind::Line => self.line.len(),
|
||||
SeriesKind::Line | SeriesKind::Bars => self.line.len(),
|
||||
_ => self.bars.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared view + plot geometry (C++ `view_first_` / `view_count_` /
|
||||
@@ -174,7 +195,7 @@ impl PlotView {
|
||||
let i1 = (self.first + self.effective_count(total)).ceil() as i32;
|
||||
for s in series {
|
||||
match s.kind {
|
||||
SeriesKind::Line => {
|
||||
SeriesKind::Line | SeriesKind::Bars => {
|
||||
for i in i0..i1 {
|
||||
if i < 0 || i as usize >= s.line.len() {
|
||||
continue;
|
||||
@@ -199,6 +220,12 @@ impl PlotView {
|
||||
if lo > hi {
|
||||
return (0.0, 1.0);
|
||||
}
|
||||
// Bars series draw from the zero line, so the range must contain
|
||||
// zero or the bars overflow the plot area below the axis.
|
||||
if series.iter().any(|s| s.kind == SeriesKind::Bars) {
|
||||
lo = lo.min(0.0);
|
||||
hi = hi.max(0.0);
|
||||
}
|
||||
let pad = (hi - lo) * 0.06 + 1e-9;
|
||||
(lo - pad, hi + pad)
|
||||
}
|
||||
@@ -400,6 +427,14 @@ impl XGraph {
|
||||
self.view.reset(0);
|
||||
}
|
||||
|
||||
/// Drop every series AND every x label, and reset the view.
|
||||
/// (`clear_series` drops the series but keeps the labels.)
|
||||
pub fn clear_data(&mut self) {
|
||||
self.series.clear();
|
||||
self.x_labels.clear();
|
||||
self.view.reset(0);
|
||||
}
|
||||
|
||||
pub fn add_line_series(&mut self, name: &str, color: Srgb, values: Vec<f64>) {
|
||||
self.series.push(GraphSeries::line_series(name, color, values));
|
||||
}
|
||||
@@ -415,6 +450,270 @@ impl XGraph {
|
||||
.push(GraphSeries::ohlc_series(name, color, bars, candlesticks));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ CSV loading
|
||||
//
|
||||
// Every loader parses with `crate::csv::parse_ohlcv_csv` (format:
|
||||
// `date,open,high,low,close[,volume]`, header row optional) and
|
||||
// returns the number of CSV rows loaded. The `load_*` loaders replace
|
||||
// all plotted data (clear-then-add); `add_ohlc_csv` appends a second
|
||||
// series (two-symbol compare). A parse error leaves the chart
|
||||
// untouched: the rows are parsed before anything is cleared.
|
||||
|
||||
fn push_ohlcv(&mut self, name: &str, rows: &[crate::csv::OhlcvRow], candlesticks: bool) {
|
||||
let bars: Vec<XGraphBar> = rows
|
||||
.iter()
|
||||
.map(|r| XGraphBar::new(r.open, r.high, r.low, r.close))
|
||||
.collect();
|
||||
self.add_ohlc_series(name, self.line_color, bars, candlesticks);
|
||||
self.x_labels.extend(rows.iter().map(|r| r.date.clone()));
|
||||
self.view.reset(self.item_count());
|
||||
}
|
||||
|
||||
fn replace_line(&mut self, name: &str, values: Vec<f64>, labels: Vec<String>) {
|
||||
self.clear_data();
|
||||
self.add_line_series(name, self.line_color, values);
|
||||
self.x_labels = labels;
|
||||
self.view.reset(self.item_count());
|
||||
}
|
||||
|
||||
fn labels_of(rows: &[crate::csv::OhlcvRow]) -> Vec<String> {
|
||||
rows.iter().map(|r| r.date.clone()).collect()
|
||||
}
|
||||
|
||||
/// Replace the chart with one OHLC series from CSV text
|
||||
/// (`candlesticks`: candles vs plain OHLC bars).
|
||||
pub fn load_ohlcv_csv(
|
||||
&mut self,
|
||||
name: &str,
|
||||
text: &str,
|
||||
candlesticks: bool,
|
||||
) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
self.clear_data();
|
||||
self.push_ohlcv(name, &rows, candlesticks);
|
||||
Ok(rows.len())
|
||||
}
|
||||
|
||||
/// Append an OHLC series from CSV text without clearing the ones
|
||||
/// already plotted (two-symbol compare: load the first symbol with
|
||||
/// `load_ohlcv_csv`, the second with this, then `add_ratio_line` /
|
||||
/// `add_spread_line`).
|
||||
pub fn add_ohlc_csv(
|
||||
&mut self,
|
||||
name: &str,
|
||||
text: &str,
|
||||
candlesticks: bool,
|
||||
) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
self.push_ohlcv(name, &rows, candlesticks);
|
||||
Ok(rows.len())
|
||||
}
|
||||
|
||||
/// Replace the chart with one line series of close prices.
|
||||
pub fn load_close_line_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let values = crate::csv::closes(&rows);
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.replace_line(name, values, labels);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with close prices indexed to 100 at the first
|
||||
/// bar (IndexedComparison / RelativePerformance / SectorComparison).
|
||||
/// Errors when the first close is 0.
|
||||
pub fn load_indexed_close_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let first = rows[0].close;
|
||||
if first == 0.0 {
|
||||
return Err("first close is 0, cannot index to 100".to_string());
|
||||
}
|
||||
let values: Vec<f64> = crate::csv::closes(&rows)
|
||||
.iter()
|
||||
.map(|c| c / first * 100.0)
|
||||
.collect();
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.replace_line(name, values, labels);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with one volume series (vertical bars from zero).
|
||||
pub fn load_volume_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let values = crate::csv::volumes(&rows);
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.clear_data();
|
||||
self.series
|
||||
.push(GraphSeries::bar_series(name, self.line_color, values));
|
||||
self.x_labels = labels;
|
||||
self.view.reset(self.item_count());
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with volume candles: each bar's open is the
|
||||
/// previous bar's volume, close the bar's own volume (up when volume
|
||||
/// grew, down when it shrank).
|
||||
pub fn load_volume_candles_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let vols = crate::csv::volumes(&rows);
|
||||
let mut bars = Vec::with_capacity(vols.len());
|
||||
for (i, &v) in vols.iter().enumerate() {
|
||||
let o = if i == 0 { v } else { vols[i - 1] };
|
||||
bars.push(XGraphBar::new(o, o.max(v), o.min(v), v));
|
||||
}
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.clear_data();
|
||||
self.add_ohlc_series(name, self.line_color, bars, true);
|
||||
self.x_labels = labels;
|
||||
self.view.reset(self.item_count());
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with the price candles plus the VWAP line
|
||||
/// (two series: the candles named `name`, the line named `"VWAP"`).
|
||||
pub fn load_vwap_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let vwap = crate::csv::vwap_line(&rows);
|
||||
let n = rows.len();
|
||||
self.clear_data();
|
||||
self.push_ohlcv(name, &rows, true);
|
||||
self.add_line_series("VWAP", self.line_color, vwap);
|
||||
self.view.reset(self.item_count());
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with the On-Balance Volume line.
|
||||
pub fn load_obv_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let values = crate::csv::obv_line(&rows);
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.replace_line(name, values, labels);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with the Accumulation/Distribution line.
|
||||
pub fn load_accum_dist_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let values = crate::csv::accum_dist_line(&rows);
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.replace_line(name, values, labels);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with the per-bar money-flow line.
|
||||
pub fn load_money_flow_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let values = crate::csv::money_flow_line(&rows);
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.replace_line(name, values, labels);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with Heikin-Ashi candles computed from the rows.
|
||||
pub fn load_heikin_ashi_csv(&mut self, name: &str, text: &str) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let bars = crate::csv::heikin_ashi_bars(&rows);
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.clear_data();
|
||||
self.add_ohlc_series(name, self.line_color, bars, true);
|
||||
self.x_labels = labels;
|
||||
self.view.reset(self.item_count());
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with fixed-brick Renko candles computed from the
|
||||
/// closes. `brick`: the brick size in price units; `None` picks 1%
|
||||
/// of the first close (at least 0.01).
|
||||
pub fn load_renko_csv(
|
||||
&mut self,
|
||||
name: &str,
|
||||
text: &str,
|
||||
brick: Option<f64>,
|
||||
) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let brick = match brick {
|
||||
Some(b) if b > 0.0 && b.is_finite() => b,
|
||||
Some(_) => return Err("renko brick size must be a positive finite number".to_string()),
|
||||
None => (rows[0].close * 0.01).max(0.01),
|
||||
};
|
||||
let bars = crate::csv::renko_bars(&rows, brick);
|
||||
let labels = Self::labels_of(&rows);
|
||||
let n = rows.len();
|
||||
self.clear_data();
|
||||
self.add_ohlc_series(name, self.line_color, bars, true);
|
||||
self.x_labels = labels;
|
||||
self.view.reset(self.item_count());
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace the chart with the volume profile: per-price-bin volume
|
||||
/// bars (`bins` bins, clamped to 1..=50) with `"lo-hi"` price labels.
|
||||
pub fn load_volume_profile_csv(
|
||||
&mut self,
|
||||
name: &str,
|
||||
text: &str,
|
||||
bins: usize,
|
||||
) -> Result<usize, String> {
|
||||
let rows = crate::csv::parse_ohlcv_csv(text)?;
|
||||
let (vols, labels) = crate::csv::volume_profile(&rows, bins);
|
||||
let n = rows.len();
|
||||
self.clear_data();
|
||||
self.series
|
||||
.push(GraphSeries::bar_series(name, self.line_color, vols));
|
||||
self.x_labels = labels;
|
||||
self.view.reset(self.item_count());
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn close_values(&self, index: usize) -> Option<Vec<f64>> {
|
||||
self.series.get(index).map(|s| match s.kind {
|
||||
SeriesKind::Line | SeriesKind::Bars => s.line.clone(),
|
||||
_ => s.bars.iter().map(|b| b.close).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn two_close_series(&self) -> Result<(Vec<f64>, Vec<f64>), String> {
|
||||
match (self.close_values(0), self.close_values(1)) {
|
||||
(Some(a), Some(b)) => Ok((a, b)),
|
||||
_ => Err(
|
||||
"needs two loaded series: load the first symbol with load_ohlcv_csv, the second with add_ohlc_csv"
|
||||
.to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a ratio line (series 0 closes / series 1 closes) on top of the
|
||||
/// two series already loaded. Returns the line length. A zero
|
||||
/// divisor plots as a gap (NaN), not a crash.
|
||||
pub fn add_ratio_line(&mut self) -> Result<usize, String> {
|
||||
let (a, b) = self.two_close_series()?;
|
||||
let values: Vec<f64> = a
|
||||
.iter()
|
||||
.zip(b.iter())
|
||||
.map(|(x, y)| if *y != 0.0 { x / y } else { f64::NAN })
|
||||
.collect();
|
||||
let n = values.len();
|
||||
self.add_line_series("Ratio", self.line_color, values);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Add a spread line (series 0 closes - series 1 closes) on top of
|
||||
/// the two series already loaded. Returns the line length.
|
||||
pub fn add_spread_line(&mut self) -> Result<usize, String> {
|
||||
let (a, b) = self.two_close_series()?;
|
||||
let values: Vec<f64> = a.iter().zip(b.iter()).map(|(x, y)| x - y).collect();
|
||||
let n = values.len();
|
||||
self.add_line_series("Spread", self.line_color, values);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
pub fn set_series_kind(&mut self, index: usize, kind: SeriesKind) {
|
||||
if let Some(s) = self.series.get_mut(index) {
|
||||
s.kind = kind;
|
||||
@@ -502,7 +801,7 @@ impl XGraph {
|
||||
continue;
|
||||
}
|
||||
match s.kind {
|
||||
SeriesKind::Line => {
|
||||
SeriesKind::Line | SeriesKind::Bars => {
|
||||
if (idx as usize) < s.line.len() {
|
||||
out.push((s.name.clone(), s.line[idx as usize]));
|
||||
}
|
||||
@@ -551,6 +850,23 @@ impl XGraph {
|
||||
}
|
||||
target.set_line_width(1);
|
||||
}
|
||||
SeriesKind::Bars => {
|
||||
// Vertical bars from the zero line (volume): one filled
|
||||
// rect per value, from y(0) to y(v).
|
||||
let bw = ((self.view.item_w(total) * 0.6) as i32).max(1);
|
||||
let y0 = self.view.y_at(0.0, lo, hi);
|
||||
for (i, &v) in s.line.iter().enumerate() {
|
||||
if !v.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let cx = self.view.x_center(i as i32, total);
|
||||
if cx < px || cx > px + pw {
|
||||
continue;
|
||||
}
|
||||
let yv = self.view.y_at(v, lo, hi);
|
||||
target.fill_rect(cx - bw / 2, yv.min(y0), bw, (y0 - yv).abs().max(1));
|
||||
}
|
||||
}
|
||||
SeriesKind::OhlcBars | SeriesKind::Candlesticks => {
|
||||
let bw = ((self.view.item_w(total) * 0.6) as i32).max(1);
|
||||
for i in 0..s.bars.len() {
|
||||
@@ -594,6 +910,11 @@ impl Widget for XGraph {
|
||||
fn kind(&self) -> &str {
|
||||
&self.kind
|
||||
}
|
||||
fn load_csv_data(&mut self, csv: &str) -> Result<usize, String> {
|
||||
// The bare XGraph widget plots OHLCV as candles.
|
||||
let name = self.state.name.clone();
|
||||
self.load_ohlcv_csv(&name, csv, true)
|
||||
}
|
||||
fn state(&self) -> &WidgetState {
|
||||
&self.state
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
//! `generator/gen_data.py`.
|
||||
|
||||
pub mod archetypes;
|
||||
pub mod csv;
|
||||
pub mod events;
|
||||
pub mod events_gen;
|
||||
pub mod graph;
|
||||
@@ -37,6 +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 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};
|
||||
|
||||
@@ -250,6 +250,17 @@ pub trait Widget {
|
||||
fn set_want_returns(&mut self, _v: bool) {}
|
||||
fn set_yalign(&mut self, _v: f64) {}
|
||||
fn set_checked_items(&mut self, _csv: &str) {}
|
||||
/// Load OHLCV CSV text into this widget (`csv::parse_ohlcv_csv`
|
||||
/// format: `date,open,high,low,close[,volume]`). Returns the number
|
||||
/// of rows loaded. Default: this widget plots no data series.
|
||||
/// Chart widgets override it (`ChartWidget` picks the series for
|
||||
/// its kind; `XGraph` loads candles).
|
||||
fn load_csv_data(&mut self, _csv: &str) -> Result<usize, String> {
|
||||
Err(format!(
|
||||
"{} plots no data series, so CSV data cannot be loaded into it",
|
||||
self.name()
|
||||
))
|
||||
}
|
||||
// --- Phase 3 (Inspector properties §2.11-§2.22) ---
|
||||
fn set_show_text(&mut self, _v: bool) {}
|
||||
fn set_pulsing(&mut self, _v: bool) {}
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
//! Stock chart CSV tests: parsing, derived series, per-kind population,
|
||||
//! clear/populate refresh, two-symbol ratio/spread, and headless renders
|
||||
//! proving the loaded CSV data actually plots (vs the blank template —
|
||||
//! a fresh chart has no series at all, so any series-coloured pixel is
|
||||
//! CSV data on screen).
|
||||
|
||||
use xframe_core::{Canvas, StyleManager};
|
||||
use xframe_widgets::archetypes::ChartWidget;
|
||||
use xframe_widgets::csv::{
|
||||
accum_dist_line, closes, heikin_ashi_bars, money_flow_line, obv_line, parse_ohlcv_csv,
|
||||
renko_bars, volume_profile, volumes, vwap_line,
|
||||
};
|
||||
use xframe_widgets::graph::SeriesKind;
|
||||
use xframe_widgets::{create, Widget, XGraph};
|
||||
|
||||
const CSV5: &str = "date,open,high,low,close,volume
|
||||
2026-01-05,10,12,9,11,100
|
||||
2026-01-06,11,13,10,12,200
|
||||
2026-01-07,12,12,11,11,150
|
||||
";
|
||||
|
||||
const SAMPLE_CSV: &str = include_str!("../../xframe-demo/examples/data/sample-ohlcv.csv");
|
||||
|
||||
fn approx(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_header_and_rows() {
|
||||
let rows = parse_ohlcv_csv(CSV5).unwrap();
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert_eq!(rows[0].date, "2026-01-05");
|
||||
assert!(approx(rows[0].open, 10.0));
|
||||
assert!(approx(rows[2].close, 11.0));
|
||||
assert!(approx(rows[2].volume, 150.0));
|
||||
assert_eq!(closes(&rows), vec![11.0, 12.0, 11.0]);
|
||||
assert_eq!(volumes(&rows), vec![100.0, 200.0, 150.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_no_header_volume_optional_comments_blanks() {
|
||||
let text = "# comment\n\n2026-01-05,10,12,9,11\n2026-01-06, 11 , 13 , 10 , 12\n";
|
||||
let rows = parse_ohlcv_csv(text).unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert!(approx(rows[0].volume, 0.0));
|
||||
assert!(approx(rows[1].close, 12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_date_formats() {
|
||||
for date in [
|
||||
"2026-01-05",
|
||||
"2026/01/05",
|
||||
"20260105",
|
||||
"1767571200",
|
||||
"2026-01-05 09:30:00",
|
||||
] {
|
||||
let text = format!("{},10,12,9,11,100\n", date);
|
||||
assert!(parse_ohlcv_csv(&text).is_ok(), "date {}", date);
|
||||
}
|
||||
let bad = "05/01/2026,10,12,9,11,100\n";
|
||||
assert!(parse_ohlcv_csv(bad).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_errors_name_the_line() {
|
||||
// Too few columns on line 3.
|
||||
let e = parse_ohlcv_csv(
|
||||
"date,open,high,low,close,volume\n2026-01-05,10,12,9,11,100\n2026-01-06,11,13\n",
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(e.contains("line 3"), "{}", e);
|
||||
// Non-numeric close on line 2.
|
||||
let e = parse_ohlcv_csv("2026-01-05,10,12,9,xx,100\n").unwrap_err();
|
||||
assert!(e.contains("line 1"), "{}", e);
|
||||
// Empty / header-only.
|
||||
assert!(parse_ohlcv_csv("").is_err());
|
||||
assert!(parse_ohlcv_csv("date,open,high,low,close,volume\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_sample_file() {
|
||||
let rows = parse_ohlcv_csv(SAMPLE_CSV).unwrap();
|
||||
assert_eq!(rows.len(), 30);
|
||||
assert_eq!(rows[0].date, "2026-01-05");
|
||||
assert_eq!(rows[29].date, "2026-02-13");
|
||||
assert!(rows.iter().all(|r| r.high >= r.open.max(r.close)));
|
||||
assert!(rows.iter().all(|r| r.low <= r.open.min(r.close)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_series_math() {
|
||||
let rows = parse_ohlcv_csv(CSV5).unwrap();
|
||||
// VWAP: typicals 10.6667 / 11.6667 / 11.3333.
|
||||
let v = vwap_line(&rows);
|
||||
assert!(approx(v[0], 32.0 / 3.0));
|
||||
assert!(approx(v[1], 3400.0 / 300.0));
|
||||
assert!(approx(v[2], 5100.0 / 450.0));
|
||||
// OBV: 100, +200, -150.
|
||||
assert_eq!(obv_line(&rows), vec![100.0, 300.0, 150.0]);
|
||||
// A/D: 100/3, +200/3, -150.
|
||||
let ad = accum_dist_line(&rows);
|
||||
assert!(approx(ad[0], 100.0 / 3.0));
|
||||
assert!(approx(ad[1], 100.0));
|
||||
assert!(approx(ad[2], -50.0));
|
||||
// Money flow is the per-bar (non-cumulative) value.
|
||||
let mf = money_flow_line(&rows);
|
||||
assert!(approx(mf[0], 100.0 / 3.0));
|
||||
assert!(approx(mf[1], 200.0 / 3.0));
|
||||
assert!(approx(mf[2], -150.0));
|
||||
// Heikin-Ashi, hand-computed.
|
||||
let ha = heikin_ashi_bars(&rows);
|
||||
assert!(approx(ha[0].open, 10.0) && approx(ha[0].close, 10.5));
|
||||
assert!(approx(ha[0].high, 12.0) && approx(ha[0].low, 9.0));
|
||||
assert!(approx(ha[1].open, 10.25) && approx(ha[1].close, 11.5));
|
||||
assert!(approx(ha[2].open, 10.875) && approx(ha[2].close, 11.5));
|
||||
// Renko, brick 1.0: up brick then down brick.
|
||||
let rk = renko_bars(&rows, 1.0);
|
||||
assert_eq!(rk.len(), 2);
|
||||
assert!(approx(rk[0].open, 11.0) && approx(rk[0].close, 12.0));
|
||||
assert!(approx(rk[1].open, 12.0) && approx(rk[1].close, 11.0));
|
||||
// Volume profile, 2 bins over [9, 13]: [100, 350].
|
||||
let (vols, labels) = volume_profile(&rows, 2);
|
||||
assert_eq!(vols, vec![100.0, 350.0]);
|
||||
assert_eq!(labels, vec!["9-11".to_string(), "11-13".to_string()]);
|
||||
}
|
||||
|
||||
/// The 23 stock kinds that plot a data series: (widget name, kind tag).
|
||||
const DATA_KINDS: &[(&str, &str)] = &[
|
||||
("StockAccumulationDistribution", "AccumulationDistribution"),
|
||||
("StockAreaChart", "AreaChart"),
|
||||
("StockBaselineChart", "BaselineChart"),
|
||||
("StockCandlestickChart", "CandlestickChart"),
|
||||
("StockCorrelationView", "CorrelationView"),
|
||||
("StockHeikinAshi", "HeikinAshi"),
|
||||
("StockHollowCandles", "HollowCandles"),
|
||||
("StockIndexedComparison", "IndexedComparison"),
|
||||
("StockLineChart", "LineChart"),
|
||||
("StockMoneyFlowChart", "MoneyFlowChart"),
|
||||
("StockMultiSymbolChart", "MultiSymbolChart"),
|
||||
("StockOBVChart", "OBVChart"),
|
||||
("StockOHLCBarChart", "OHLCBarChart"),
|
||||
("StockOverlayChart", "OverlayChart"),
|
||||
("StockRatioChart", "RatioChart"),
|
||||
("StockRelativePerformance", "RelativePerformance"),
|
||||
("StockRenko", "Renko"),
|
||||
("StockSectorComparison", "SectorComparison"),
|
||||
("StockSpreadChart", "SpreadChart"),
|
||||
("StockVWAP", "VWAP"),
|
||||
("StockVolumeBars", "VolumeBars"),
|
||||
("StockVolumeCandles", "VolumeCandles"),
|
||||
("StockVolumeProfile", "VolumeProfile"),
|
||||
];
|
||||
|
||||
/// The 14 drawing/annotation kinds: no data input, CSV load must fail.
|
||||
const DRAWING_KINDS: &[&str] = &[
|
||||
"StockArrow",
|
||||
"StockBrush",
|
||||
"StockEllipse",
|
||||
"StockFibExtension",
|
||||
"StockFibRetracement",
|
||||
"StockHorizontalLine",
|
||||
"StockMeasureTool",
|
||||
"StockParallelChannel",
|
||||
"StockPitchfork",
|
||||
"StockPriceLabel",
|
||||
"StockRectangle",
|
||||
"StockTextAnnotation",
|
||||
"StockTrendline",
|
||||
"StockVerticalLine",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn every_data_kind_plots_the_sample_csv() {
|
||||
for (name, kind) in DATA_KINDS {
|
||||
let mut w = create(name).unwrap_or_else(|| panic!("no widget {}", name));
|
||||
assert_eq!(w.kind(), *kind);
|
||||
let n = w
|
||||
.load_csv_data(SAMPLE_CSV)
|
||||
.unwrap_or_else(|e| panic!("{} failed to load CSV: {}", name, e));
|
||||
assert_eq!(n, 30, "{}", name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_kinds_reject_csv() {
|
||||
for name in DRAWING_KINDS {
|
||||
let mut w = create(name).unwrap();
|
||||
assert!(w.load_csv_data(SAMPLE_CSV).is_err(), "{}", name);
|
||||
}
|
||||
// A non-chart widget rejects CSV too (default trait method).
|
||||
let mut b = create("GtkButton").unwrap();
|
||||
assert!(b.load_csv_data(SAMPLE_CSV).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn populate_series_shapes() {
|
||||
// VWAP plots two series: candles + the VWAP line.
|
||||
let mut vwap = ChartWidget::new("StockVWAP", "VWAP", 0, 0, 400, 300);
|
||||
assert_eq!(vwap.populate_from_csv(SAMPLE_CSV).unwrap(), 30);
|
||||
assert_eq!(vwap.graph.series.len(), 2);
|
||||
assert_eq!(vwap.graph.series[0].kind, SeriesKind::Candlesticks);
|
||||
assert_eq!(vwap.graph.series[1].name, "VWAP");
|
||||
assert_eq!(vwap.graph.series[1].kind, SeriesKind::Line);
|
||||
// VolumeProfile plots 10 volume bars with price-bin labels.
|
||||
let mut vp = ChartWidget::new("StockVolumeProfile", "VolumeProfile", 0, 0, 400, 300);
|
||||
assert_eq!(vp.populate_from_csv(SAMPLE_CSV).unwrap(), 30);
|
||||
assert_eq!(vp.graph.series[0].kind, SeriesKind::Bars);
|
||||
assert_eq!(vp.graph.series[0].len(), 10);
|
||||
assert_eq!(vp.graph.x_labels.len(), 10);
|
||||
// IndexedComparison plots closes indexed to 100 at the first bar.
|
||||
let mut idx = ChartWidget::new(
|
||||
"StockIndexedComparison",
|
||||
"IndexedComparison",
|
||||
0,
|
||||
0,
|
||||
400,
|
||||
300,
|
||||
);
|
||||
idx.populate_from_csv(SAMPLE_CSV).unwrap();
|
||||
assert!(approx(idx.graph.series[0].line[0], 100.0));
|
||||
// Renko plots bricks, not the 30 input bars.
|
||||
let mut rk = ChartWidget::new("StockRenko", "Renko", 0, 0, 400, 300);
|
||||
rk.populate_from_csv(SAMPLE_CSV).unwrap();
|
||||
assert_eq!(rk.graph.series[0].kind, SeriesKind::Candlesticks);
|
||||
assert!(!rk.graph.series[0].bars.is_empty());
|
||||
// A failed load leaves the previous data in place.
|
||||
let before = rk.graph.series[0].len();
|
||||
assert!(rk.populate_from_csv("nonsense\n").is_err());
|
||||
assert_eq!(rk.graph.series[0].len(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_then_populate_refresh() {
|
||||
let mut w = ChartWidget::new("StockCandlestickChart", "CandlestickChart", 0, 0, 400, 300);
|
||||
w.populate_from_csv(SAMPLE_CSV).unwrap();
|
||||
assert_eq!(w.graph.series.len(), 1);
|
||||
assert_eq!(w.graph.x_labels.len(), 30);
|
||||
// Re-populating replaces, never accumulates.
|
||||
w.populate_from_csv(CSV5).unwrap();
|
||||
assert_eq!(w.graph.series.len(), 1);
|
||||
assert_eq!(w.graph.series[0].len(), 3);
|
||||
assert_eq!(w.graph.x_labels.len(), 3);
|
||||
// Clear drops series and labels.
|
||||
w.clear_data();
|
||||
assert!(w.graph.series.is_empty());
|
||||
assert!(w.graph.x_labels.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_y_range_contains_zero() {
|
||||
// Bars draw from the zero line: the range must contain 0, or the
|
||||
// bars overflow the plot area below the axis.
|
||||
let mut g = XGraph::new("XGraph", 0, 0, 400, 300);
|
||||
g.load_volume_csv("v", SAMPLE_CSV).unwrap();
|
||||
let (lo, hi) = g.y_range();
|
||||
assert!(lo < 0.0, "lo {}", lo);
|
||||
assert!(hi > 1_000_000.0, "hi {}", hi);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_symbol_ratio_and_spread() {
|
||||
let mut g = XGraph::new("XGraph", 0, 0, 400, 300);
|
||||
assert!(g.add_ratio_line().is_err());
|
||||
g.load_ohlcv_csv("A", SAMPLE_CSV, true).unwrap();
|
||||
g.add_ohlc_csv("B", SAMPLE_CSV, true).unwrap();
|
||||
let n = g.add_ratio_line().unwrap();
|
||||
assert_eq!(n, 30);
|
||||
assert!(g.series[2].line.iter().all(|v| approx(*v, 1.0)));
|
||||
g.add_spread_line().unwrap();
|
||||
assert!(g.series[3].line.iter().all(|v| approx(*v, 0.0)));
|
||||
}
|
||||
|
||||
fn canvas(w: i32, h: i32) -> (Canvas, StyleManager) {
|
||||
(Canvas::new(w, h), StyleManager::new())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_data_renders_and_blank_chart_does_not() {
|
||||
// Blank (template) chart: no series, so no series-coloured pixels.
|
||||
let (mut target, mut styles) = canvas(400, 300);
|
||||
let blank = ChartWidget::new("StockCandlestickChart", "CandlestickChart", 0, 0, 400, 300);
|
||||
blank.draw(&mut target, &mut styles);
|
||||
let blank_candles = target.count_pixels(0x009600) + target.count_pixels(0xc81e1e);
|
||||
assert_eq!(blank_candles, 0);
|
||||
|
||||
// Same widget + CSV: candle bodies and wicks are on screen.
|
||||
let (mut target, mut styles) = canvas(400, 300);
|
||||
let mut w = ChartWidget::new("StockCandlestickChart", "CandlestickChart", 0, 0, 400, 300);
|
||||
w.populate_from_csv(SAMPLE_CSV).unwrap();
|
||||
w.draw(&mut target, &mut styles);
|
||||
let candles = target.count_pixels(0x009600) + target.count_pixels(0xc81e1e);
|
||||
assert!(candles > 100, "candles painted: {}", candles);
|
||||
|
||||
// Line chart: the close line is on screen in the kind's line colour.
|
||||
let (mut target, mut styles) = canvas(400, 300);
|
||||
let mut line = ChartWidget::new("StockLineChart", "LineChart", 0, 0, 400, 300);
|
||||
line.populate_from_csv(SAMPLE_CSV).unwrap();
|
||||
line.draw(&mut target, &mut styles);
|
||||
assert!(target.count_pixels(0x0064c8) > 50);
|
||||
|
||||
// Volume bars: vertical bars in the kind's line colour.
|
||||
let (mut target, mut styles) = canvas(400, 300);
|
||||
let mut vol = ChartWidget::new("StockVolumeBars", "VolumeBars", 0, 0, 400, 300);
|
||||
vol.populate_from_csv(SAMPLE_CSV).unwrap();
|
||||
vol.draw(&mut target, &mut styles);
|
||||
assert!(target.count_pixels(0x0064c8) > 500);
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
# Stock chart widgets: how plotting data gets in (Rust)
|
||||
|
||||
How the 37 `Stock*` widgets in `lightgui_rust` ingest data, what sample
|
||||
data ships with them (none — see below), and how to plot your own CSV.
|
||||
The reference implementation is `crates/xframe-widgets/src/csv.rs`
|
||||
(parser + derived series) and the loaders on `XGraph`
|
||||
(`crates/xframe-widgets/src/graph.rs`).
|
||||
|
||||
## The short version
|
||||
|
||||
```rust
|
||||
use xframe_widgets::{create, Widget};
|
||||
|
||||
let mut chart = create("StockCandlestickChart").unwrap();
|
||||
chart.set_bounds(40, 40, 720, 520);
|
||||
let csv = std::fs::read_to_string(
|
||||
"crates/xframe-demo/examples/data/sample-ohlcv.csv",
|
||||
).unwrap();
|
||||
let rows = chart.load_csv_data(&csv).expect("sample CSV loads");
|
||||
assert_eq!(rows, 30); // 30 bars plotted
|
||||
```
|
||||
|
||||
Or from the shell, with a live window under Xvfb:
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo -- StockCandlestickChart \
|
||||
--csv crates/xframe-demo/examples/data/sample-ohlcv.csv \
|
||||
--geometry 20,20,760,560 --hold 5
|
||||
```
|
||||
|
||||
## Audit: how data gets in today
|
||||
|
||||
All 37 `Stock*` kinds are one archetype, `ChartWidget`
|
||||
(`crates/xframe-widgets/src/archetypes.rs`), wrapping one `XGraph`
|
||||
(`crates/xframe-widgets/src/graph.rs`). There are not 547 structs: the
|
||||
`kind` string (e.g. `"CandlestickChart"`) specialises the archetype.
|
||||
|
||||
### Data model
|
||||
|
||||
`XGraph` holds a list of `GraphSeries`:
|
||||
|
||||
| Series kind | Stored as | Drawn as |
|
||||
| --- | --- | --- |
|
||||
| `Line` | `line: Vec<f64>` | polyline |
|
||||
| `OhlcBars` | `bars: Vec<XGraphBar{open,high,low,close}>` | OHLC ticks |
|
||||
| `Candlesticks` | `bars: Vec<XGraphBar>` | candle bodies + wicks |
|
||||
| `Bars` | `line: Vec<f64>` | vertical bars from the zero line (volume) |
|
||||
|
||||
plus `x_labels: Vec<String>` (one label per bar, shown on the time
|
||||
axis) and a `PlotView` (first/count window, auto-y with 6% padding,
|
||||
wheel zoom, drag pan, crosshair). There is **no volume field on a bar
|
||||
and no timestamp field**: volume lives in its own series, dates live
|
||||
only as string labels.
|
||||
|
||||
### Setters (the API before CSV existed)
|
||||
|
||||
| Method | What it does |
|
||||
| --- | --- |
|
||||
| `add_line_series(name, colour, values)` | append a line series |
|
||||
| `add_ohlc_series(name, colour, bars, candlesticks)` | append an OHLC/candle series |
|
||||
| `clear_series()` | drop every series (keeps x labels) |
|
||||
| `clear_data()` | drop every series **and** every x label |
|
||||
| `set_x_labels(labels)` | replace the x labels |
|
||||
| `set_y_range(lo, hi)` / `set_auto_y(bool)` | fix the y range / back to auto |
|
||||
| `reset_view()` / `zoom_at(factor, frac)` | show all / zoom around a point |
|
||||
| `set_series_kind(i, kind)` / `set_series_color(i, c)` / `set_series_up_down(i, up, down)` | retarget one series |
|
||||
|
||||
There was no `set_data` / `add_point` / `populate` and no CSV loader
|
||||
anywhere in the repo. The typical refresh is clear-then-add, then
|
||||
redraw.
|
||||
|
||||
### Template / sample data: there is none inside the widget
|
||||
|
||||
A fresh `ChartWidget` / `XGraph` has an **empty series list and draws
|
||||
nothing** — a blank background. No literal sample arrays and no seeded
|
||||
series are baked into the Rust chart code. (The C repo has
|
||||
`make_seeded_series(n, 42)` in `widgets/components/StockData.h`; the
|
||||
Rust port of that generator lives in
|
||||
`crates/xframe-widgets/src/indicators.rs` as `demo_bars(n)` and feeds
|
||||
the `Ind*` indicator widgets only, not the `Stock*` charts. The
|
||||
comment in `crates/lightgui-gen/src/gen.rs` that used to say
|
||||
"StockCandlestickChart draws its seeded preview series" was wrong and
|
||||
has been corrected.) The repo's sample data is the file
|
||||
`crates/xframe-demo/examples/data/sample-ohlcv.csv`: 30 weekday bars,
|
||||
2026-01-05..2026-02-13, a random walk starting at 100.00.
|
||||
|
||||
### The `kind` string does not change what is drawn
|
||||
|
||||
`ChartWidget::draw` delegates straight to `XGraph::draw`, which draws
|
||||
whatever series are present. Two kinds given the same series render
|
||||
identically — the kind only decides *which* series `populate_from_csv`
|
||||
builds (see the table below). Per-kind transforms that exist in the C
|
||||
widgets (Heikin-Ashi, Renko, VWAP, OBV, …) are computed here in
|
||||
`csv.rs` at load time, not in the draw path. Annotation overlays
|
||||
(Trendline, FibRetracement, …) are stored (`set_anchor(bar, price)`,
|
||||
`set_color`) but the Rust chart draws no overlays yet.
|
||||
|
||||
## 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 the header above is recognised
|
||||
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, and the whole load fails — the chart is left
|
||||
untouched, because the rows are parsed before anything is cleared.
|
||||
An empty file (or header only) is an error.
|
||||
* No network, no live market data, no API keys.
|
||||
|
||||
The parser is `xframe_widgets::csv::parse_ohlcv_csv` (also exported as
|
||||
`xframe_widgets::parse_ohlcv_csv`); rows are `OhlcvRow { date, open,
|
||||
high, low, close, volume }`.
|
||||
|
||||
## Per-kind table: what `populate_from_csv` plots
|
||||
|
||||
`ChartWidget::populate_from_csv(text)` (or the generic
|
||||
`Widget::load_csv_data(text)`, which forwards to it) picks the series
|
||||
for the kind. It returns the number of CSV rows loaded. Every loader
|
||||
replaces all plotted data (clear-then-add).
|
||||
|
||||
| Widget | Plots from one CSV | Loader used |
|
||||
| --- | --- | --- |
|
||||
| `StockCandlestickChart` | OHLC as candles | `load_ohlcv_csv(…, true)` |
|
||||
| `StockHollowCandles` | OHLC as candles (hollow up-bodies are not rendered distinctly yet — same candles) | `load_ohlcv_csv(…, true)` |
|
||||
| `StockOHLCBarChart` | OHLC as plain bars | `load_ohlcv_csv(…, false)` |
|
||||
| `StockHeikinAshi` | Heikin-Ashi candles, computed from the rows | `load_heikin_ashi_csv` |
|
||||
| `StockRenko` | Fixed-brick Renko candles from the closes; brick defaults to 1% of the first close (min 0.01), or pass one to `load_renko_csv` | `load_renko_csv(…, None)` |
|
||||
| `StockLineChart` | Close line | `load_close_line_csv` |
|
||||
| `StockAreaChart` | Close line (no fill yet — same line) | `load_close_line_csv` |
|
||||
| `StockBaselineChart` | Close line (no baseline fill yet — same line) | `load_close_line_csv` |
|
||||
| `StockCorrelationView` | Close line (single series; a second symbol is needed for a real correlation — see below) | `load_close_line_csv` |
|
||||
| `StockMultiSymbolChart` | Close line (single series; add a second with `add_ohlc_csv`) | `load_close_line_csv` |
|
||||
| `StockOverlayChart` | Close line (single series; add a second with `add_ohlc_csv`) | `load_close_line_csv` |
|
||||
| `StockRatioChart` | Close line (single series; for a real ratio load two series, then `add_ratio_line`) | `load_close_line_csv` |
|
||||
| `StockSpreadChart` | Close line (single series; for a real spread load two series, then `add_spread_line`) | `load_close_line_csv` |
|
||||
| `StockIndexedComparison` | Closes indexed to 100 at the first bar | `load_indexed_close_csv` |
|
||||
| `StockRelativePerformance` | Closes indexed to 100 at the first bar | `load_indexed_close_csv` |
|
||||
| `StockSectorComparison` | Closes indexed to 100 at the first bar | `load_indexed_close_csv` |
|
||||
| `StockVWAP` | Price candles **plus** the VWAP line (2 series; the line is named `"VWAP"`) | `load_vwap_csv` |
|
||||
| `StockOBVChart` | On-Balance Volume line | `load_obv_csv` |
|
||||
| `StockMoneyFlowChart` | Per-bar money-flow line (`multiplier * volume`, not cumulative) | `load_money_flow_csv` |
|
||||
| `StockAccumulationDistribution` | Accumulation/Distribution line (cumulative money flow) | `load_accum_dist_csv` |
|
||||
| `StockVolumeBars` | Volume bars from the zero line | `load_volume_csv` |
|
||||
| `StockVolumeCandles` | Volume candles (open = previous bar's volume, close = this bar's volume) | `load_volume_candles_csv` |
|
||||
| `StockVolumeProfile` | 10-bin volume profile: per-price-bin volume bars, `"lo-hi"` price labels | `load_volume_profile_csv(…, 10)` |
|
||||
|
||||
Derived-series definitions (`csv.rs`): VWAP is cumulative
|
||||
`typical * volume / cumulative volume` with
|
||||
`typical = (high + low + close) / 3` (zero-volume bars fall back to the
|
||||
typical price); OBV starts at the first bar's volume and adds /
|
||||
subtracts the bar's volume when the close rose / fell; the money-flow
|
||||
multiplier is `((close − low) − (high − close)) / (high − low)`
|
||||
(0 when high == low); A/D is its cumulative `multiplier * volume`;
|
||||
Heikin-Ashi is `ha_close = (o+h+l+c)/4`,
|
||||
`ha_open = (prev_ha_open + prev_ha_close)/2` (first bar: the raw open);
|
||||
Renko steps a fixed brick from the first close (capped at 50,000
|
||||
bricks); the volume profile buckets typical price into 10 bins over
|
||||
`[min low, max high]`.
|
||||
|
||||
### Drawing-only kinds (no data input)
|
||||
|
||||
These 14 plot no data series. `populate_from_csv` / `load_csv_data`
|
||||
returns an error naming the kind; `xframe-demo --csv` on one exits 2
|
||||
with that message. Position them with `set_anchor(bar, price)` instead.
|
||||
|
||||
`StockArrow`, `StockBrush`, `StockEllipse`, `StockFibExtension`,
|
||||
`StockFibRetracement`, `StockHorizontalLine`, `StockMeasureTool`,
|
||||
`StockParallelChannel`, `StockPitchfork`, `StockPriceLabel`,
|
||||
`StockRectangle`, `StockTextAnnotation`, `StockTrendline`,
|
||||
`StockVerticalLine`.
|
||||
|
||||
## Worked examples
|
||||
|
||||
### Clear / populate refresh
|
||||
|
||||
```rust
|
||||
use xframe_widgets::{create, Widget};
|
||||
|
||||
let mut chart = create("StockLineChart").unwrap();
|
||||
let csv = std::fs::read_to_string("data.csv").unwrap();
|
||||
chart.load_csv_data(&csv).unwrap(); // 30 closes plotted
|
||||
|
||||
// New file arrives: re-populate replaces, never accumulates.
|
||||
let csv2 = std::fs::read_to_string("data2.csv").unwrap();
|
||||
chart.load_csv_data(&csv2).unwrap();
|
||||
|
||||
// Or clear explicitly, then add series by hand.
|
||||
chart.load_csv_data(&csv).unwrap();
|
||||
// (no clear_data on the trait; drop down to the concrete widget:)
|
||||
let mut chart = xframe_widgets::archetypes::ChartWidget::new(
|
||||
"StockLineChart", "LineChart", 0, 0, 720, 520,
|
||||
);
|
||||
chart.populate_from_csv(&csv).unwrap();
|
||||
chart.clear_data(); // series + x labels gone; chart is blank again
|
||||
assert!(chart.graph.series.is_empty());
|
||||
```
|
||||
|
||||
### Two-symbol ratio / spread
|
||||
|
||||
```rust
|
||||
use xframe_widgets::{Widget, XGraph, XGraphBar};
|
||||
|
||||
// XGraph-level loaders: load the first symbol, append the second,
|
||||
// then derive the line from the two close series.
|
||||
let mut g = XGraph::new("XGraph", 0, 0, 720, 520);
|
||||
let a = std::fs::read_to_string("symbol-a.csv").unwrap();
|
||||
let b = std::fs::read_to_string("symbol-b.csv").unwrap();
|
||||
g.load_ohlcv_csv("A", &a, true).unwrap();
|
||||
g.add_ohlc_csv("B", &b, true).unwrap();
|
||||
g.add_ratio_line().unwrap(); // series "Ratio": A closes / B closes
|
||||
g.add_spread_line().unwrap(); // series "Spread": A closes - B closes
|
||||
```
|
||||
|
||||
A zero divisor in the ratio plots as a gap (NaN), not a crash.
|
||||
`add_ratio_line` / `add_spread_line` error when fewer than two
|
||||
series are loaded.
|
||||
|
||||
### Loading without the widget: parse + derived series
|
||||
|
||||
```rust
|
||||
use xframe_widgets::csv::{parse_ohlcv_csv, vwap_line, obv_line};
|
||||
|
||||
let rows = parse_ohlcv_csv(&std::fs::read_to_string("data.csv").unwrap()).unwrap();
|
||||
let vwap = vwap_line(&rows);
|
||||
let obv = obv_line(&rows);
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
* `cargo test -p xframe-widgets --test csv_tests`: 13 tests — parser
|
||||
(header / no header / optional volume / comments / date formats /
|
||||
errors naming the line), derived-series math against hand-computed
|
||||
values, all 23 data kinds loading the 30-row sample file, all 14
|
||||
drawing kinds rejecting it, clear/populate refresh, two-symbol
|
||||
ratio/spread, and headless `Canvas` renders proving the CSV data is
|
||||
on screen (candle pixels > 100 where the blank chart has 0).
|
||||
* `cargo run -p xframe-demo --example csv-chart-shots` renders all 23
|
||||
kinds headlessly at 760×560 and diffs each against the blank
|
||||
template: every kind differs by 5,888–131,949 pixels (least:
|
||||
the close-line kinds at 5,888; most: `StockVolumeBars`).
|
||||
* Live under Xvfb: `xframe-demo StockCandlestickChart --csv
|
||||
sample-ohlcv.csv` and `StockVolumeBars --csv …` show the CSV data
|
||||
with axis labels and legend; `StockTrendline --csv …` exits 2 with
|
||||
the drawing-overlay error. Screenshots are not committed to the
|
||||
repo; regenerate them with the `csv-chart-shots` example.
|
||||
|
||||
## Limits, honestly stated
|
||||
|
||||
* **One file, one symbol, per load.** `populate_from_csv` plots one
|
||||
CSV. Multi-symbol kinds (`MultiSymbolChart`, `OverlayChart`,
|
||||
`CorrelationView`, `RatioChart`, `SpreadChart`) plot that file's
|
||||
close line (or indexed closes) until a second file is appended with
|
||||
`add_ohlc_csv` + `add_ratio_line` / `add_spread_line`.
|
||||
* **The kind does not change the rendering.** `AreaChart` has no fill
|
||||
yet and `BaselineChart` has no baseline fill; `HollowCandles` draws
|
||||
the same solid candles as `CandlestickChart`. The per-kind
|
||||
difference today is which series the loader builds.
|
||||
* **No separate volume pane.** Volume is its own series on the same
|
||||
axes (bars from the zero line — the y range is forced to contain 0
|
||||
when a `Bars` series is present, so the bars stay inside the plot).
|
||||
* **Dates are labels only.** The x axis shows the CSV date strings;
|
||||
there is no time-scale-aware axis (no weekend gaps, no intraday
|
||||
spacing).
|
||||
* **Overlays are stored, not drawn.** `set_anchor` / `set_color` on
|
||||
the drawing kinds record the geometry; the chart draws no overlay
|
||||
shapes yet.
|
||||
* **No live data.** Nothing here fetches prices. The sample CSV is
|
||||
synthetic; bring your own file (or generate one — the C repo's
|
||||
`make_seeded_series` is the deterministic generator the `Ind*`
|
||||
widgets use).
|
||||
* **Renko brick default** is 1% of the first close. For a $3 stock
|
||||
that is $0.03 bricks (hundreds of bricks); for a $3,000 stock it is
|
||||
$30 bricks (very few). Pass an explicit brick to `load_renko_csv`
|
||||
when the default does not fit the price level.
|
||||
|
||||
## See also
|
||||
|
||||
* `crates/xframe-widgets/src/csv.rs` — parser + derived series
|
||||
(the CSV format spec lives in its module docs).
|
||||
* `crates/xframe-widgets/src/graph.rs` — `XGraph` loaders,
|
||||
`SeriesKind::Bars`, the zero-baseline y range.
|
||||
* `crates/xframe-demo/src/lib.rs` — `run_widget_with_csv` and the
|
||||
`--csv` flag of the `xframe-demo` binary.
|
||||
* `crates/xframe-demo/examples/csv-chart-shots.rs` — headless
|
||||
per-kind renders + blank-template diff.
|
||||
* `crates/xframe-demo/examples/data/sample-ohlcv.csv` — the 30-row
|
||||
sample file.
|
||||
* Doc blog: <https://rustdoc.lightgui.com/> — each widget page has a
|
||||
"Plotting your own data (CSV)" section.
|
||||
Reference in new issue
Block a user