SPB Git

spb/wp40_uqo

Public MIT
1.9 KB · 35 lines cpp
1#include "raid/data/io.hpp"2#include "raid/core/error.hpp"3#include <fstream>4#include <sstream>5#include <charconv>67namespace raid::data {89std::map<std::string, BarSeries> read_bars_csv(const std::string& path, Interval iv) {10  std::ifstream f(path); RAID_REQUIRE(f.good(), io, "cannot open " + path);11  std::string line; std::getline(f, line);12  RAID_REQUIRE(line.rfind("symbol,timestamp_utc,open,high,low,close,volume", 0) == 0, io, "unexpected CSV header in " + path + ": " + line);13  std::map<std::string, BarSeries> out;14  usize ln = 1;15  while (std::getline(f, line)) {16    ++ln; if (line.empty()) continue;17    std::string cells[7]; usize c = 0, start = 0;18    for (usize i = 0; i <= line.size() && c < 7; ++i) if (i == line.size() || line[i] == ',') { cells[c++] = line.substr(start, i - start); start = i + 1; }19    RAID_REQUIRE(c == 7, io, "bad CSV row " + std::to_string(ln) + " in " + path);20    auto num = [&](const std::string& s) { f64 v; const auto r = std::from_chars(s.data(), s.data() + s.size(), v); RAID_REQUIRE(r.ec == std::errc{}, io, "bad number '" + s + "' row " + std::to_string(ln)); return v; };21    auto& bs = out[cells[0]]; if (bs.symbol.empty()) { bs.symbol = cells[0]; bs.instrument_id = "synthetic:" + cells[0]; bs.interval = iv; bs.adjustment = "synthetic"; }22    bs.push_back(timestamp_from_iso(cells[1]), num(cells[2]), num(cells[3]), num(cells[4]), num(cells[5]), num(cells[6]));23  }24  for (auto& [k, bs] : out) bs.index_sessions();25  return out;26}2728void write_bars_csv(const std::string& path, const BarSeries& b) {29  std::ofstream f(path); RAID_REQUIRE(f.good(), io, "cannot write " + path);30  f << "symbol,timestamp_utc,open,high,low,close,volume\n"; f.precision(10);31  for (usize i = 0; i < b.size(); ++i) f << b.symbol << ',' << timestamp_iso(b.t_open[i]) << ',' << b.open[i] << ',' << b.high[i] << ',' << b.low[i] << ',' << b.close[i] << ',' << b.volume[i] << '\n';32}3334}  // namespace raid::data35
Files · main
Menu

Theme