Every chart widget rendered only the baked-in 250-bar demo series: no set_series existed in Python despite the docstring naming it, so there was no way to plot real data at all. Now StockWidget holds up to three series slots (primary + two extra for the multi-symbol charts) via set_series (the C API), get_series, add_point, clear / populate, item_count, and load_csv; all 37 draw paths read the widget series through _bars(widget) instead of module DEMO_SERIES, so derived series (Heikin-Ashi, Renko, VWAP, OBV, ...) rebuild from the loaded data and the drawing tools inherit it as background. load_csv reads date,open,high,low,close,volume with the stdlib csv module: header optional (matched by name, any order, extra columns ignored), dates YYYY-MM-DD / YYYY/MM/DD / DD-MM-YYYY / ISO datetime / epoch seconds (validated, not stored -- the x-axis is bar index), ValueError naming the row on bad data. A cleared series draws a no-data placeholder; a one-bar series draws (Price: flat change). Tests: tests/test_stock_csv.py, 27 tests (parsing, API, headless renders of all 24 chart kinds incl. CSV-vs-template pixel diff). Fixture tests/data/ohlcv_30.csv (30 weekday bars). Full suite 311 tests pass; visreg 24/24 stock charts pixel-identical to template goldens. Docs: docs/stock-charts-data.md. Screenshots: tools/stock_csv_shots.py (Xvfb, RMSE 9-35% vs template goldens).
328 lines
13 KiB
Python
328 lines
13 KiB
Python
"""Stock chart data ingestion: CSV loading + set_series/clear/populate.
|
|
|
|
- ``load_csv`` (module function + ``StockWidget.load_csv``): the
|
|
tests/data/ohlcv_30.csv fixture (30 real weekday bars), header /
|
|
no-header / shuffled-columns / date formats, and every ValueError
|
|
path naming the offending row.
|
|
- Series API: set/get round-trip, ``set_series(None)`` restores the
|
|
demo series, ``add_point`` starts a fresh series, ``clear`` /
|
|
``populate``, ``item_count``, view reset on ``set_series``.
|
|
- Rendering: every in-scope chart kind (the 24 that plot a data
|
|
series) draws CSV data headless without raising, the CSV render
|
|
differs from the template render (proving the CSV data is what is
|
|
plotted), a one-bar series draws, and a cleared series draws the
|
|
no-data placeholder.
|
|
"""
|
|
import io
|
|
import os
|
|
import unittest
|
|
|
|
import cairo
|
|
|
|
from lightgui.xframe import core
|
|
from lightgui.xframe import stock as stock_mod
|
|
|
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
CSV_PATH = os.path.join(REPO, "tests", "data", "ohlcv_30.csv")
|
|
|
|
# The 13 Stock kinds that are pure drawing tools (anchors, no data
|
|
# input) -- everything else in STOCK_KINDS plots a data series.
|
|
TOOL_KINDS = frozenset((
|
|
"Arrow", "Brush", "Ellipse", "FibExtension", "FibRetracement",
|
|
"HorizontalLine", "MeasureTool", "ParallelChannel", "Pitchfork",
|
|
"Rectangle", "TextAnnotation", "Trendline", "VerticalLine",
|
|
))
|
|
CHART_KINDS = sorted(stock_mod.STOCK_KINDS - TOOL_KINDS)
|
|
CHART_NAMES = {"Stock" + k if k != "Price" else "StockPriceLabel"
|
|
for k in CHART_KINDS}
|
|
|
|
|
|
def _make(name, width=400, height=300):
|
|
widget = core.create(name, name + "_001", 0, 0, width, height)
|
|
assert widget is not None, name
|
|
return widget
|
|
|
|
|
|
def _draw(widget):
|
|
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
|
|
widget.width + 4, widget.height + 4)
|
|
cr = cairo.Context(surface)
|
|
cr.set_source_rgb(1, 1, 1)
|
|
cr.paint()
|
|
widget.draw(cr)
|
|
return surface
|
|
|
|
|
|
def _png_bytes(surface):
|
|
buf = io.BytesIO()
|
|
surface.write_to_png(buf)
|
|
return buf.getvalue()
|
|
|
|
|
|
def _non_white_pixels(surface):
|
|
data = surface.get_data()
|
|
stride = surface.get_stride()
|
|
count = 0
|
|
for y in range(surface.get_height()):
|
|
row = data[y * stride:(y + 1) * stride]
|
|
for x in range(0, len(row), 4):
|
|
b, g, r = row[x], row[x + 1], row[x + 2]
|
|
if (r, g, b) != (255, 255, 255):
|
|
count += 1
|
|
return count
|
|
|
|
|
|
def _csv_text(rows, header="date,open,high,low,close,volume"):
|
|
lines = [header] if header is not None else []
|
|
lines += [",".join(str(c) for c in row) for row in rows]
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
GOOD_ROWS = [
|
|
("2026-03-02", 50.0, 51.0, 49.5, 50.5, 100000),
|
|
("2026-03-03", 50.5, 52.0, 50.0, 51.5, 120000),
|
|
("2026-03-04", 51.5, 51.8, 50.8, 51.0, 90000),
|
|
]
|
|
|
|
|
|
class LoadCsvTests(unittest.TestCase):
|
|
def test_fixture_loads_30_rows(self):
|
|
bars = stock_mod.load_csv(CSV_PATH)
|
|
self.assertEqual(len(bars), 30)
|
|
self.assertEqual(bars[0], (100.0, 100.18, 98.8, 99.4, 530827.0))
|
|
self.assertEqual(bars[-1][3], 95.71)
|
|
for open_v, high, low, close, volume in bars:
|
|
self.assertGreaterEqual(high, max(open_v, close))
|
|
self.assertLessEqual(low, min(open_v, close))
|
|
self.assertGreater(volume, 0)
|
|
|
|
def test_no_header(self):
|
|
text = _csv_text(GOOD_ROWS, header=None)
|
|
bars = stock_mod.load_csv(io.StringIO(text))
|
|
self.assertEqual(bars, [tuple(map(float, r[1:]))
|
|
for r in GOOD_ROWS])
|
|
|
|
def test_columns_matched_by_name_shuffled_plus_extra(self):
|
|
rows = [(r[0], r[5], r[4], r[3], r[2], r[1], 51.25)
|
|
for r in GOOD_ROWS]
|
|
text = _csv_text(
|
|
rows, header="date,volume,close,low,high,open,adj close")
|
|
bars = stock_mod.load_csv(io.StringIO(text))
|
|
self.assertEqual(bars, [tuple(map(float, r[1:]))
|
|
for r in GOOD_ROWS])
|
|
|
|
def test_aliases_and_date_formats(self):
|
|
rows = [
|
|
("2026/03/02", 50.0, 51.0, 49.5, 50.5, 100000),
|
|
("02-03-2026", 50.5, 52.0, 50.0, 51.5, 120000),
|
|
("2026-03-04 09:30:00", 51.5, 51.8, 50.8, 51.0, 90000),
|
|
("1772323200", 51.0, 51.5, 50.5, 51.2, 110000),
|
|
]
|
|
text = _csv_text(rows, header="timestamp,o,h,l,c,vol")
|
|
bars = stock_mod.load_csv(io.StringIO(text))
|
|
self.assertEqual(len(bars), 4)
|
|
self.assertEqual(bars[0], (50.0, 51.0, 49.5, 50.5, 100000.0))
|
|
|
|
def test_bad_float_names_row(self):
|
|
text = _csv_text([("2026-03-02", 50.0, "xx", 49.5, 50.5, 100)])
|
|
with self.assertRaises(ValueError) as ctx:
|
|
stock_mod.load_csv(io.StringIO(text))
|
|
self.assertIn("row 2", str(ctx.exception))
|
|
self.assertIn("high", str(ctx.exception))
|
|
|
|
def test_bad_date_names_row(self):
|
|
text = _csv_text([("not-a-date", 50.0, 51.0, 49.5, 50.5, 100)])
|
|
with self.assertRaises(ValueError) as ctx:
|
|
stock_mod.load_csv(io.StringIO(text))
|
|
self.assertIn("row 2", str(ctx.exception))
|
|
|
|
def test_high_below_close_suggests_column_order(self):
|
|
text = _csv_text([("2026-03-02", 51.0, 50.0, 49.5, 50.5, 100)])
|
|
with self.assertRaises(ValueError) as ctx:
|
|
stock_mod.load_csv(io.StringIO(text))
|
|
self.assertIn("column order", str(ctx.exception))
|
|
|
|
def test_negative_volume(self):
|
|
text = _csv_text([("2026-03-02", 50.0, 51.0, 49.5, 50.5, -5)])
|
|
with self.assertRaises(ValueError):
|
|
stock_mod.load_csv(io.StringIO(text))
|
|
|
|
def test_short_row_and_wrong_column_count(self):
|
|
text = _csv_text([("2026-03-02", 50.0, 51.0, 49.5, 50.5)])
|
|
with self.assertRaises(ValueError) as ctx:
|
|
stock_mod.load_csv(io.StringIO(text))
|
|
self.assertIn("row 2", str(ctx.exception))
|
|
|
|
def test_partial_header_names_missing_column(self):
|
|
text = "date,open,high,low,close\n2026-03-02,50,51,49.5,50.5\n"
|
|
with self.assertRaises(ValueError) as ctx:
|
|
stock_mod.load_csv(io.StringIO(text))
|
|
self.assertIn("volume", str(ctx.exception))
|
|
|
|
def test_empty_and_header_only_raise(self):
|
|
with self.assertRaises(ValueError):
|
|
stock_mod.load_csv(io.StringIO(""))
|
|
with self.assertRaises(ValueError):
|
|
stock_mod.load_csv(io.StringIO("date,open,high,low,close,volume\n"))
|
|
|
|
def test_missing_file_raises(self):
|
|
with self.assertRaises(OSError):
|
|
stock_mod.load_csv(os.path.join(REPO, "tests", "data",
|
|
"no-such-file.csv"))
|
|
|
|
|
|
class SeriesApiTests(unittest.TestCase):
|
|
def test_set_get_round_trip_and_copy(self):
|
|
widget = _make("StockLineChart")
|
|
bars = stock_mod.load_csv(CSV_PATH)
|
|
widget.set_series(bars)
|
|
self.assertEqual(widget.get_series(), bars)
|
|
got = widget.get_series()
|
|
got.append((1.0, 2.0, 0.5, 1.5, 10.0))
|
|
self.assertEqual(widget.item_count(), 30) # copy, not alias
|
|
|
|
def test_set_series_none_restores_demo(self):
|
|
widget = _make("StockLineChart")
|
|
widget.set_series(stock_mod.load_csv(CSV_PATH))
|
|
self.assertEqual(widget.item_count(), 30)
|
|
widget.set_series(None)
|
|
self.assertEqual(widget.get_series(), stock_mod.DEMO_SERIES)
|
|
self.assertEqual(widget.item_count(), 250)
|
|
|
|
def test_set_series_dict_bars_and_validation(self):
|
|
widget = _make("StockLineChart")
|
|
widget.set_series([{"open": 1.0, "high": 2.0, "low": 0.5,
|
|
"close": 1.5, "volume": 10.0}])
|
|
self.assertEqual(widget.get_series(),
|
|
[(1.0, 2.0, 0.5, 1.5, 10.0)])
|
|
with self.assertRaises(ValueError):
|
|
widget.set_series([(1.0, 2.0)]) # too short
|
|
with self.assertRaises(ValueError):
|
|
widget.set_series([(1.0, 0.5, 2.0, 1.5, 10.0)]) # high < low
|
|
|
|
def test_set_series_bad_slot(self):
|
|
widget = _make("StockLineChart")
|
|
with self.assertRaises(ValueError):
|
|
widget.set_series([], which=4)
|
|
|
|
def test_add_point_starts_fresh(self):
|
|
widget = _make("StockLineChart")
|
|
self.assertEqual(widget.item_count(), 250) # demo until fed
|
|
n = widget.add_point((10.0, 11.0, 9.5, 10.5, 1000.0))
|
|
self.assertEqual(n, 1)
|
|
self.assertEqual(widget.item_count(), 1)
|
|
self.assertEqual(widget.get_series(),
|
|
[(10.0, 11.0, 9.5, 10.5, 1000.0)])
|
|
with self.assertRaises(ValueError):
|
|
widget.add_point((1.0, 2.0)) # malformed bar
|
|
|
|
def test_clear_populate_workflow(self):
|
|
widget = _make("StockCandlestickChart")
|
|
widget.load_csv(CSV_PATH)
|
|
self.assertEqual(widget.item_count(), 30)
|
|
widget.clear()
|
|
self.assertEqual(widget.item_count(), 0)
|
|
self.assertEqual(widget.get_series(), [])
|
|
widget.populate(stock_mod.load_csv(CSV_PATH))
|
|
self.assertEqual(widget.item_count(), 30)
|
|
|
|
def test_clear_one_slot_only(self):
|
|
widget = _make("StockOverlayChart")
|
|
widget.set_series(stock_mod.load_csv(CSV_PATH), which=2)
|
|
self.assertEqual(widget.item_count(2), 30)
|
|
self.assertEqual(widget.item_count(1), 250) # demo untouched
|
|
widget.clear(which=2)
|
|
self.assertEqual(widget.item_count(2), 0)
|
|
self.assertEqual(widget.item_count(1), 250)
|
|
with self.assertRaises(ValueError):
|
|
widget.clear(which=5)
|
|
|
|
def test_load_csv_method_returns_count_and_keeps_old_on_error(self):
|
|
widget = _make("StockLineChart")
|
|
self.assertEqual(widget.load_csv(CSV_PATH), 30)
|
|
bad = io.StringIO("date,open,high,low,close,volume\n"
|
|
"2026-03-02,50,bad,49.5,50.5,100\n")
|
|
with self.assertRaises(ValueError):
|
|
widget.load_csv(bad)
|
|
self.assertEqual(widget.item_count(), 30) # untouched
|
|
|
|
def test_view_resets_on_set_series(self):
|
|
widget = _make("StockCandlestickChart")
|
|
widget.set_prop("view-first", "10")
|
|
widget.set_prop("view-count", "50")
|
|
widget.set_series(stock_mod.load_csv(CSV_PATH))
|
|
self.assertEqual(widget.get_prop("view-first", ""), "")
|
|
self.assertEqual(widget.get_prop("view-count", ""), "")
|
|
|
|
def test_demo_series_never_mutated(self):
|
|
first = stock_mod.DEMO_SERIES[0]
|
|
widget = _make("StockCandlestickChart")
|
|
widget.load_csv(CSV_PATH)
|
|
_draw(widget)
|
|
self.assertEqual(stock_mod.DEMO_SERIES[0], first)
|
|
self.assertEqual(len(stock_mod.DEMO_SERIES), 250)
|
|
|
|
|
|
class CsvRenderTests(unittest.TestCase):
|
|
def test_all_chart_kinds_draw_csv_data(self):
|
|
bars = stock_mod.load_csv(CSV_PATH)
|
|
for name in sorted(CHART_NAMES):
|
|
widget = _make(name)
|
|
widget.load_csv(CSV_PATH)
|
|
surface = _draw(widget) # must not raise
|
|
self.assertGreater(_non_white_pixels(surface), 100,
|
|
"%s drew nothing with CSV data" % name)
|
|
# Multi-symbol kinds also plot their extra slots.
|
|
if name in ("StockCorrelationView", "StockIndexedComparison",
|
|
"StockMultiSymbolChart", "StockOverlayChart",
|
|
"StockRatioChart", "StockRelativePerformance",
|
|
"StockSectorComparison", "StockSpreadChart"):
|
|
widget.set_series(bars, which=2)
|
|
if name in ("StockMultiSymbolChart",
|
|
"StockRelativePerformance",
|
|
"StockSectorComparison"):
|
|
widget.set_series(bars, which=3)
|
|
surface = _draw(widget)
|
|
self.assertGreater(_non_white_pixels(surface), 100, name)
|
|
|
|
def test_csv_render_differs_from_template(self):
|
|
# The CSV data must be what is plotted: same widget, same
|
|
# size, template render vs CSV render must differ a lot.
|
|
for name in ("StockCandlestickChart", "StockLineChart",
|
|
"StockVolumeBars", "StockVWAP", "StockPriceLabel"):
|
|
template = _draw(_make(name))
|
|
csv_widget = _make(name)
|
|
csv_widget.load_csv(CSV_PATH)
|
|
csv_render = _draw(csv_widget)
|
|
self.assertNotEqual(_png_bytes(template),
|
|
_png_bytes(csv_render), name)
|
|
self.assertGreater(_non_white_pixels(template), 100, name)
|
|
self.assertGreater(_non_white_pixels(csv_render), 100, name)
|
|
|
|
def test_one_bar_series_draws_every_chart_kind(self):
|
|
for name in sorted(CHART_NAMES):
|
|
widget = _make(name)
|
|
widget.set_series([(100.0, 101.0, 99.0, 100.5, 500000.0)])
|
|
_draw(widget) # must not raise (Price: no previous close)
|
|
|
|
def test_cleared_series_draws_placeholder(self):
|
|
for name in sorted(CHART_NAMES):
|
|
widget = _make(name)
|
|
widget.load_csv(CSV_PATH)
|
|
widget.clear()
|
|
surface = _draw(widget) # must not raise
|
|
self.assertGreater(_non_white_pixels(surface), 50,
|
|
"%s drew nothing when cleared" % name)
|
|
|
|
def test_tool_kinds_inherit_loaded_series_as_background(self):
|
|
# Drawing tools take no data input, but they draw over the
|
|
# candle chart, so a loaded series changes their background.
|
|
template = _draw(_make("StockTrendline"))
|
|
tool = _make("StockTrendline")
|
|
tool.load_csv(CSV_PATH)
|
|
self.assertNotEqual(_png_bytes(template), _png_bytes(_draw(tool)))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|