- xframe::load_ohlcv_csv / parse_ohlcv_csv_text in StockData.h: date,open,high,low,close,volume, optional header matched by name (Massive exports load as-is), YYYY-MM-DD / ISO / epoch s-ms-ns dates, volume optional, malformed rows skipped + counted, error string out. - 15 single-series widgets gain load_csv() + clear_series(); 8 comparative widgets gain add_series_csv(); failure leaves the series untouched. Drawing tools intentionally excluded (coordinates, not series); Ind* widgets take CSV only via the constructor. - Fixtures tests/data/ohlcv_sample.csv (+ _b, 30 rows each) and widgets/tests/csv_unit_test.cpp + test_stock_csv.py (23/23 PASS: CSV shot differs from template shot, 30 items, bad path exits 2). - docs/stock-market-csv-data.md + CSV sections in the stock group docs.
386 lines
15 KiB
C++
386 lines
15 KiB
C++
// StockData.h — shared OHLCV series type and deterministic seeded synthetic
|
|
// data for the XFrame Stock Market widget section.
|
|
//
|
|
// No network, no live market data, no API keys: demos and tests run on
|
|
// synthetic data generated here, so results are reproducible.
|
|
// Attribution: XFrame.
|
|
#pragma once
|
|
|
|
#include <cmath>
|
|
#include <cstdint>
|
|
#include <vector>
|
|
#include <cstdlib>
|
|
#include <fstream>
|
|
#include <sstream>
|
|
#include <string>
|
|
|
|
namespace xframe {
|
|
|
|
// One OHLCV bar. timestamp is seconds since the epoch (daily bars).
|
|
struct OHLCV {
|
|
double open = 0.0;
|
|
double high = 0.0;
|
|
double low = 0.0;
|
|
double close = 0.0;
|
|
double volume = 0.0;
|
|
std::int64_t timestamp = 0;
|
|
};
|
|
|
|
using OHLCVSeries = std::vector<OHLCV>;
|
|
|
|
namespace detail {
|
|
// xorshift64*: small, fast, deterministic on every platform.
|
|
inline std::uint64_t stock_next(std::uint64_t &state) {
|
|
std::uint64_t x = state;
|
|
x ^= x >> 12;
|
|
x ^= x << 25;
|
|
x ^= x >> 27;
|
|
state = x;
|
|
return x * 0x2545F4914F6CDD1DULL;
|
|
}
|
|
// Uniform double in [0, 1).
|
|
inline double stock_uniform(std::uint64_t &state) {
|
|
return (stock_next(state) >> 11) * (1.0 / 9007199254740992.0);
|
|
}
|
|
} // namespace detail
|
|
|
|
// Deterministic seeded synthetic OHLCV series: a random walk starting at
|
|
// 100.0, daily bars from 2026-01-01 UTC. Same (n, seed) gives the identical
|
|
// series on every run and every platform.
|
|
inline OHLCVSeries make_seeded_series(int n, unsigned seed = 42) {
|
|
OHLCVSeries out;
|
|
if (n <= 0) return out;
|
|
out.reserve(static_cast<std::size_t>(n));
|
|
std::uint64_t state = 0x9E3779B97F4A7C15ULL ^
|
|
(static_cast<std::uint64_t>(seed) * 0xBF58476D1CE4E5B9ULL);
|
|
if (state == 0) state = 0x2545F4914F6CDD1DULL;
|
|
const std::int64_t day0 = 1767225600; // 2026-01-01 00:00:00 UTC
|
|
double prev_close = 100.0;
|
|
for (int i = 0; i < n; ++i) {
|
|
const double open = prev_close;
|
|
const double shock = (detail::stock_uniform(state) - 0.5) * 2.4;
|
|
double close = open + 0.02 + shock;
|
|
if (!(close > 1.0)) close = 1.0 + detail::stock_uniform(state);
|
|
const double high = (open > close ? open : close) +
|
|
detail::stock_uniform(state) * 0.9;
|
|
const double low = (open < close ? open : close) -
|
|
detail::stock_uniform(state) * 0.9;
|
|
const double volume =
|
|
500000.0 + detail::stock_uniform(state) * 1500000.0;
|
|
out.push_back(OHLCV{open, high, low, close, volume,
|
|
day0 + static_cast<std::int64_t>(i) * 86400});
|
|
prev_close = close;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
inline std::vector<double> series_opens(const OHLCVSeries &s) {
|
|
std::vector<double> v;
|
|
v.reserve(s.size());
|
|
for (const auto &b : s) v.push_back(b.open);
|
|
return v;
|
|
}
|
|
|
|
inline std::vector<double> series_highs(const OHLCVSeries &s) {
|
|
std::vector<double> v;
|
|
v.reserve(s.size());
|
|
for (const auto &b : s) v.push_back(b.high);
|
|
return v;
|
|
}
|
|
|
|
inline std::vector<double> series_lows(const OHLCVSeries &s) {
|
|
std::vector<double> v;
|
|
v.reserve(s.size());
|
|
for (const auto &b : s) v.push_back(b.low);
|
|
return v;
|
|
}
|
|
|
|
inline std::vector<double> series_closes(const OHLCVSeries &s) {
|
|
std::vector<double> v;
|
|
v.reserve(s.size());
|
|
for (const auto &b : s) v.push_back(b.close);
|
|
return v;
|
|
}
|
|
|
|
inline std::vector<double> series_volumes(const OHLCVSeries &s) {
|
|
std::vector<double> v;
|
|
v.reserve(s.size());
|
|
for (const auto &b : s) v.push_back(b.volume);
|
|
return v;
|
|
}
|
|
|
|
// Typical price (high + low + close) / 3, one value per bar.
|
|
inline std::vector<double> series_typical(const OHLCVSeries &s) {
|
|
std::vector<double> v;
|
|
v.reserve(s.size());
|
|
for (const auto &b : s) v.push_back((b.high + b.low + b.close) / 3.0);
|
|
return v;
|
|
}
|
|
|
|
|
|
// ---- CSV loading ---------------------------------------------------------
|
|
// load_ohlcv_csv / parse_ohlcv_csv_text: read OHLCV bars from a CSV file
|
|
// (or string) into the shared OHLCVSeries model, so any chart widget can
|
|
// plot a real data file instead of the seeded template series:
|
|
//
|
|
// std::string err;
|
|
// auto series = xframe::load_ohlcv_csv("aapl_30d.csv", err);
|
|
// if (!err.empty()) { /* report err; series is empty */ }
|
|
// chart.set_series(series); // or chart.load_csv(path, err)
|
|
//
|
|
// Format (one bar per line):
|
|
// date,open,high,low,close,volume
|
|
// - A header row is OPTIONAL. When the first non-empty line is a header,
|
|
// columns are matched BY NAME and may appear in any order. Recognised
|
|
// names (case-insensitive): date, timestamp, time, window_start, open,
|
|
// high, low, close, volume. Anything else (ticker, transactions,
|
|
// adj_close, ...) is ignored, so Massive aggregates exports load as-is.
|
|
// Without a header the columns are positional:
|
|
// date,open,high,low,close,volume.
|
|
// - Dates are read as UTC: YYYY-MM-DD, YYYY/MM/DD, YYYY-MM-DD HH:MM:SS
|
|
// (or a T separator, optional trailing Z), or an epoch timestamp:
|
|
// seconds (>= 1e9), milliseconds (>= 1e12), nanoseconds (>= 1e15,
|
|
// Massive window_start).
|
|
// - volume is optional and defaults to 0. A missing date column -- or a
|
|
// headerless 5-column file open,high,low,close,volume -- gets sequential
|
|
// daily timestamps starting 2026-01-01 UTC.
|
|
// - Blank lines are skipped; a row that does not parse is skipped and
|
|
// counted in *skipped. On failure the returned series is empty and
|
|
// `error` explains why: unreadable file, missing open/high/low/close
|
|
// columns, or no valid rows.
|
|
// - Well-formed rows satisfy high >= max(open, close) and
|
|
// low <= min(open, close); the loader keeps the file's values as-is
|
|
// and does not repair them.
|
|
|
|
namespace detail {
|
|
|
|
// Days since 1970-01-01 for a civil date (Howard Hinnant's algorithm;
|
|
// pure arithmetic, no timezone, no mktime).
|
|
inline std::int64_t stock_days_from_civil(int y, unsigned m, unsigned d) {
|
|
y -= m <= 2;
|
|
const std::int64_t era = (y >= 0 ? y : y - 399) / 400;
|
|
const unsigned yoe = static_cast<unsigned>(y - era * 400);
|
|
const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
|
|
const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
|
return era * 146097 + static_cast<std::int64_t>(doe) - 719468;
|
|
}
|
|
|
|
inline std::string stock_trim(const std::string& s) {
|
|
size_t b = s.find_first_not_of(" \t\r\n");
|
|
if (b == std::string::npos) return std::string();
|
|
size_t e = s.find_last_not_of(" \t\r\n");
|
|
return s.substr(b, e - b + 1);
|
|
}
|
|
|
|
// Split one CSV line on commas, honouring double-quoted fields ("" is a
|
|
// literal quote). Returned fields are trimmed; surrounding quotes removed.
|
|
inline std::vector<std::string> stock_split_csv(const std::string& line) {
|
|
std::vector<std::string> fields;
|
|
std::string cur;
|
|
bool quoted = false;
|
|
for (size_t i = 0; i < line.size(); ++i) {
|
|
char c = line[i];
|
|
if (quoted) {
|
|
if (c == '"') {
|
|
if (i + 1 < line.size() && line[i + 1] == '"') { cur += '"'; ++i; }
|
|
else quoted = false;
|
|
} else cur += c;
|
|
} else if (c == '"') {
|
|
quoted = true;
|
|
} else if (c == ',') {
|
|
fields.push_back(stock_trim(cur));
|
|
cur.clear();
|
|
} else cur += c;
|
|
}
|
|
fields.push_back(stock_trim(cur));
|
|
return fields;
|
|
}
|
|
|
|
inline bool stock_parse_double(const std::string& s, double& out) {
|
|
if (s.empty()) return false;
|
|
char* end = nullptr;
|
|
out = std::strtod(s.c_str(), &end);
|
|
return end != s.c_str() && *end == '\0';
|
|
}
|
|
|
|
inline bool stock_parse_int(const std::string& s, std::int64_t& out) {
|
|
if (s.empty()) return false;
|
|
size_t i = (s[0] == '-' || s[0] == '+') ? 1 : 0;
|
|
if (i >= s.size()) return false;
|
|
for (size_t j = i; j < s.size(); ++j)
|
|
if (s[j] < '0' || s[j] > '9') return false;
|
|
char* end = nullptr;
|
|
out = std::strtoll(s.c_str(), &end, 10);
|
|
return end != s.c_str() && *end == '\0';
|
|
}
|
|
|
|
// Parse a date into epoch seconds (UTC). Accepts YYYY-MM-DD, YYYY/MM/DD,
|
|
// optional " HH:MM[:SS]" or "THH:MM[:SS]" (+ trailing Z), or a bare epoch
|
|
// timestamp (s / ms / ns by magnitude).
|
|
inline bool stock_parse_date(const std::string& s, std::int64_t& out) {
|
|
if (s.size() >= 10 && (s[4] == '-' || s[4] == '/') && s[7] == s[4]) {
|
|
std::int64_t y = 0, mo = 0, d = 0;
|
|
if (!stock_parse_int(s.substr(0, 4), y) ||
|
|
!stock_parse_int(s.substr(5, 2), mo) ||
|
|
!stock_parse_int(s.substr(8, 2), d))
|
|
return false;
|
|
if (y < 1970 || y > 2100 || mo < 1 || mo > 12 || d < 1 || d > 31)
|
|
return false;
|
|
std::int64_t secs = stock_days_from_civil((int)y, (unsigned)mo,
|
|
(unsigned)d) * 86400;
|
|
if (s.size() > 10 && (s[10] == ' ' || s[10] == 'T')) {
|
|
std::int64_t hh = 0, mm = 0, ss = 0;
|
|
if (s.size() < 16) return false;
|
|
if (!stock_parse_int(s.substr(11, 2), hh) ||
|
|
!stock_parse_int(s.substr(14, 2), mm))
|
|
return false;
|
|
if (s.size() >= 19 && s[16] == ':') {
|
|
if (!stock_parse_int(s.substr(17, 2), ss)) return false;
|
|
}
|
|
if (hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 60)
|
|
return false;
|
|
secs += hh * 3600 + mm * 60 + ss;
|
|
}
|
|
out = secs;
|
|
return true;
|
|
}
|
|
std::int64_t v = 0;
|
|
if (!stock_parse_int(s, v)) return false;
|
|
if (v >= 1000000000000000LL) v /= 1000000000LL; // ns -> s
|
|
else if (v >= 1000000000000LL) v /= 1000; // ms -> s
|
|
if (v < 1000000000LL) return false; // before 2001: not a date
|
|
out = v;
|
|
return true;
|
|
}
|
|
|
|
inline std::string stock_lower(std::string s) {
|
|
for (char& c : s)
|
|
if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
|
|
return s;
|
|
}
|
|
|
|
} // namespace detail
|
|
|
|
// Parse OHLCV bars from CSV text. Returns the series (empty + `error` set
|
|
// on failure). `skipped` (if given) receives the count of malformed rows
|
|
// that were skipped.
|
|
inline OHLCVSeries parse_ohlcv_csv_text(const std::string& text,
|
|
std::string& error,
|
|
int* skipped = nullptr) {
|
|
error.clear();
|
|
if (skipped) *skipped = 0;
|
|
OHLCVSeries out;
|
|
std::string body = text;
|
|
// Strip a UTF-8 BOM.
|
|
if (body.size() >= 3 && (unsigned char)body[0] == 0xEF &&
|
|
(unsigned char)body[1] == 0xBB && (unsigned char)body[2] == 0xBF)
|
|
body = body.substr(3);
|
|
std::istringstream in(body);
|
|
std::string line;
|
|
// Column map: -1 = absent. Positional default is date,open,high,low,
|
|
// close,volume.
|
|
int c_date = 0, c_open = 1, c_high = 2, c_low = 3, c_close = 4, c_vol = 5;
|
|
bool have_header = false;
|
|
bool seen_first = false;
|
|
const std::int64_t day0 = 1767225600; // 2026-01-01 00:00:00 UTC
|
|
auto skip_row = [&]() { if (skipped) ++(*skipped); };
|
|
while (std::getline(in, line)) {
|
|
if (detail::stock_trim(line).empty()) continue;
|
|
std::vector<std::string> f = detail::stock_split_csv(line);
|
|
if (!seen_first) {
|
|
seen_first = true;
|
|
std::int64_t probe = 0;
|
|
double num = 0;
|
|
bool first_is_date = detail::stock_parse_date(f[0], probe);
|
|
bool first_is_num = detail::stock_parse_double(f[0], num);
|
|
if (!first_is_date && !first_is_num) {
|
|
// Header row: match columns by name.
|
|
have_header = true;
|
|
c_date = c_open = c_high = c_low = c_close = c_vol = -1;
|
|
for (size_t i = 0; i < f.size(); ++i) {
|
|
std::string n = detail::stock_lower(f[i]);
|
|
if (n == "date" || n == "timestamp" || n == "time" ||
|
|
n == "window_start") c_date = (int)i;
|
|
else if (n == "open") c_open = (int)i;
|
|
else if (n == "high") c_high = (int)i;
|
|
else if (n == "low") c_low = (int)i;
|
|
else if (n == "close") c_close = (int)i;
|
|
else if (n == "volume" || n == "vol") c_vol = (int)i;
|
|
}
|
|
if (c_open < 0 || c_high < 0 || c_low < 0 || c_close < 0) {
|
|
std::string missing;
|
|
if (c_open < 0) missing += " open";
|
|
if (c_high < 0) missing += " high";
|
|
if (c_low < 0) missing += " low";
|
|
if (c_close < 0) missing += " close";
|
|
error = "CSV header is missing required column(s):" + missing;
|
|
return OHLCVSeries{};
|
|
}
|
|
continue;
|
|
}
|
|
// No header: positional. A 5-field numeric row is
|
|
// open,high,low,close,volume (no date column).
|
|
if (!first_is_date && f.size() == 5) {
|
|
c_date = -1; c_open = 0; c_high = 1; c_low = 2; c_close = 3; c_vol = 4;
|
|
}
|
|
}
|
|
int need = std::max(std::max(c_open, c_high),
|
|
std::max(c_low, c_close));
|
|
if (c_date >= 0) need = std::max(need, c_date);
|
|
if (c_vol >= 0) need = std::max(need, c_vol);
|
|
if ((int)f.size() <= need) { skip_row(); continue; }
|
|
OHLCV b;
|
|
double o = 0, h = 0, l = 0, c = 0, v = 0;
|
|
if (!detail::stock_parse_double(f[(size_t)c_open], o) ||
|
|
!detail::stock_parse_double(f[(size_t)c_high], h) ||
|
|
!detail::stock_parse_double(f[(size_t)c_low], l) ||
|
|
!detail::stock_parse_double(f[(size_t)c_close], c)) {
|
|
skip_row(); continue;
|
|
}
|
|
if (c_vol >= 0 && !f[(size_t)c_vol].empty() &&
|
|
!detail::stock_parse_double(f[(size_t)c_vol], v)) {
|
|
skip_row(); continue;
|
|
}
|
|
std::int64_t ts = day0 + (std::int64_t)out.size() * 86400;
|
|
if (c_date >= 0) {
|
|
if (!detail::stock_parse_date(f[(size_t)c_date], ts)) {
|
|
skip_row(); continue;
|
|
}
|
|
}
|
|
b.open = o; b.high = h; b.low = l; b.close = c; b.volume = v;
|
|
b.timestamp = ts;
|
|
out.push_back(b);
|
|
}
|
|
(void)have_header;
|
|
if (!seen_first) { error = "CSV file is empty"; return OHLCVSeries{}; }
|
|
if (out.empty()) {
|
|
error = "CSV file has no valid OHLCV rows";
|
|
if (skipped && *skipped > 0)
|
|
error += " (" + std::to_string(*skipped) + " row(s) skipped)";
|
|
return OHLCVSeries{};
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// Load OHLCV bars from a CSV file at `path`. Returns the series (empty +
|
|
// `error` set on failure: unreadable file, bad header, or no valid rows).
|
|
inline OHLCVSeries load_ohlcv_csv(const std::string& path,
|
|
std::string& error,
|
|
int* skipped = nullptr) {
|
|
error.clear();
|
|
std::ifstream f(path);
|
|
if (!f) {
|
|
error = "cannot open CSV file: " + path;
|
|
return OHLCVSeries{};
|
|
}
|
|
std::ostringstream ss;
|
|
ss << f.rdbuf();
|
|
if (f.bad()) {
|
|
error = "cannot read CSV file: " + path;
|
|
return OHLCVSeries{};
|
|
}
|
|
return parse_ohlcv_csv_text(ss.str(), error, skipped);
|
|
}
|
|
|
|
} // namespace xframe
|