Skip to main content

oa/data/
ohlcv.rs

1//! OHLCV views adapted from `trade/include/oa/core/database.h` (OaDataOhlcv)
2//! and `trade/lib/oa/core/dataframe.cpp` (FromOhlcvData). Explicit timestamp
3//! units, full validation and borrowed windows replace donor copies/f64 time.
4
5pub use super::types::OhlcvWindowConfig;
6use super::{DataFrame, DataFrameView, Dataset, Sample, SeriesView};
7use crate::{Error, Matrix, Result, Runtime};
8use std::ops::Range;
9
10/// Unit of exact signed Unix timestamps; negative values precede the epoch.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum UnixTimeUnit {
13	/// Seconds since 1970-01-01T00:00:00Z.
14	Seconds,
15	/// Milliseconds since the epoch.
16	Milliseconds,
17	/// Microseconds since the epoch.
18	Microseconds,
19	/// Nanoseconds since the epoch.
20	Nanoseconds,
21}
22
23/// Validated borrowed candles. Prices and volume accept F32 or F64 columns;
24/// timestamps are I64. Source columns remain immutable while this view exists.
25#[derive(Clone, Copy, Debug)]
26pub struct OhlcvView<'a> {
27	timestamps: &'a [i64],
28	unit: UnixTimeUnit,
29	columns: [SeriesView<'a>; 5],
30}
31
32impl<'a> OhlcvView<'a> {
33	/// Borrow timestamp/open/high/low/close/volume columns by their standard names.
34	///
35	/// # Errors
36	/// Rejects missing/wrongly typed columns, non-finite values, negative volume,
37	/// inconsistent candle bounds, or timestamps not strictly increasing.
38	pub fn new_from_frame(frame: &'a DataFrame, unit: UnixTimeUnit) -> Result<Self> {
39		Self::new_from_frame_view(frame.slice(0..frame.len())?, unit)
40	}
41
42	/// Validate and borrow candles inside one existing frame row partition.
43	///
44	/// # Errors
45	/// Uses the same column, timestamp and candle validation as `from_frame`.
46	pub fn new_from_frame_view(frame: DataFrameView<'a>, unit: UnixTimeUnit) -> Result<Self> {
47		let SeriesView::I64(timestamps) = frame.column("timestamp")? else {
48			return Err(Error::invalid_argument(
49				"OHLCV timestamps must be exact I64 integers",
50			));
51		};
52		let columns = [
53			frame.column("open")?,
54			frame.column("high")?,
55			frame.column("low")?,
56			frame.column("close")?,
57			frame.column("volume")?,
58		];
59		if columns
60			.iter()
61			.any(|column| matches!(column, SeriesView::I64(_)))
62		{
63			return Err(Error::invalid_argument(
64				"OHLCV prices and volume require F32 or F64 columns",
65			));
66		}
67		if timestamps.windows(2).any(|pair| pair[0] >= pair[1]) {
68			return Err(Error::invalid_argument(
69				"OHLCV timestamps must be strictly increasing",
70			));
71		}
72		for row in 0..timestamps.len() {
73			let values = columns.map(|column| column.float_at(row).expect("frame lengths validated"));
74			let [open, high, low, close, volume] = values;
75			if values.iter().any(|v| !v.is_finite())
76				|| volume < 0.0
77				|| low > open
78				|| low > close
79				|| high < open
80				|| high < close
81				|| low > high
82			{
83				return Err(Error::invalid_argument(format!(
84					"invalid OHLCV candle at row {row}"
85				)));
86			}
87		}
88		Ok(Self {
89			timestamps,
90			unit,
91			columns,
92		})
93	}
94
95	/// Exact timestamp storage.
96	pub fn timestamps(self) -> &'a [i64] {
97		self.timestamps
98	}
99
100	/// Timestamp unit, preserved by every view.
101	pub fn time_unit(self) -> UnixTimeUnit {
102		self.unit
103	}
104
105	/// Columns in open/high/low/close/volume order.
106	pub fn columns(self) -> [SeriesView<'a>; 5] {
107		self.columns
108	}
109
110	/// Number of candles.
111	pub fn len(self) -> usize {
112		self.timestamps.len()
113	}
114
115	/// Whether there are no candles.
116	pub fn is_empty(self) -> bool {
117		self.timestamps.is_empty()
118	}
119
120	/// Borrow a row interval without rescanning or copying validated candles.
121	///
122	/// # Errors
123	/// Rejects reversed or out-of-bounds intervals.
124	pub fn slice(self, range: Range<usize>) -> Result<Self> {
125		if range.start > range.end || range.end > self.len() {
126			return Err(Error::out_of_range("OHLCV row range is outside the source"));
127		}
128		let columns = [
129			self.columns[0].slice(range.clone())?,
130			self.columns[1].slice(range.clone())?,
131			self.columns[2].slice(range.clone())?,
132			self.columns[3].slice(range.clone())?,
133			self.columns[4].slice(range.clone())?,
134		];
135		Ok(Self {
136			timestamps: &self.timestamps[range],
137			unit: self.unit,
138			columns,
139		})
140	}
141
142	/// Partition raw rows before creating windows, avoiding cross-split leakage.
143	///
144	/// # Errors
145	/// Rejects boundaries outside the source or in descending order.
146	pub fn chronological_split(self, train_end: usize, validation_end: usize) -> Result<[Self; 3]> {
147		if train_end > validation_end || validation_end > self.len() {
148			return Err(Error::out_of_range(
149				"OHLCV split boundaries must be ordered and within rows",
150			));
151		}
152		Ok([
153			self.slice(0..train_end)?,
154			self.slice(train_end..validation_end)?,
155			self.slice(validation_end..self.len())?,
156		])
157	}
158}
159
160/// Host-only borrowed sliding windows. Construct separately within each split.
161#[derive(Clone, Copy, Debug)]
162pub struct OhlcvWindows<'a> {
163	source: OhlcvView<'a>,
164	config: OhlcvWindowConfig,
165	count: i64,
166}
167
168impl<'a> OhlcvWindows<'a> {
169	/// Number of complete windows.
170	pub fn len(&self) -> i64 {
171		self.count
172	}
173
174	/// Whether no complete window fits.
175	pub fn is_empty(&self) -> bool {
176		self.count == 0
177	}
178
179	/// Construct checked windows over one chronological partition.
180	///
181	/// # Errors
182	/// Rejects zero dimensions/stride or shape/count overflow.
183	pub fn new(source: OhlcvView<'a>, config: OhlcvWindowConfig) -> Result<Self> {
184		let span = config
185			.lookback
186			.checked_add(config.horizon)
187			.ok_or_else(|| Error::invalid_argument("OHLCV window extent overflow"))?;
188		if config.lookback == 0
189			|| config.horizon == 0
190			|| config.stride == 0
191			|| config.lookback.checked_mul(5).is_none()
192		{
193			return Err(Error::invalid_argument(
194				"OHLCV windows require positive checked extents and stride",
195			));
196		}
197		let count = if source.len() < span {
198			0
199		} else {
200			(source.len() - span) / config.stride + 1
201		};
202		let count = i64::try_from(count)
203			.map_err(|_| Error::invalid_argument("OHLCV window count exceeds i64"))?;
204		Ok(Self {
205			source,
206			config,
207			count,
208		})
209	}
210
211	/// Borrow input and future-label candle intervals without allocation.
212	///
213	/// # Errors
214	/// Rejects negative/out-of-range indices.
215	pub fn window(&self, index: i64) -> Result<(OhlcvView<'a>, OhlcvView<'a>)> {
216		if index < 0 || index >= self.count {
217			return Err(Error::out_of_range("OHLCV window index outside dataset"));
218		}
219		let start = index as usize * self.config.stride;
220		let middle = start + self.config.lookback;
221		Ok((
222			self.source.slice(start..middle)?,
223			self.source.slice(middle..middle + self.config.horizon)?,
224		))
225	}
226}
227
228/// Runtime-borrowing adapter for the existing Dataset/DataLoader contract.
229///
230/// Host windows borrow columns. `get_sample` packs row-major FP32 [lookback, 5]
231/// input and `horizon` future-close labels and uploads each once. Timestamps
232/// remain metadata, never float features. No normalization or readback occurs.
233/// Host windowing is zero-copy; packing and device upload are explicit copies.
234pub struct OhlcvDataset<'a> {
235	runtime: &'a Runtime,
236	windows: OhlcvWindows<'a>,
237}
238
239impl<'a> OhlcvDataset<'a> {
240	/// Attach an existing checked host window set to a borrowed Runtime.
241	pub fn new(runtime: &'a Runtime, windows: OhlcvWindows<'a>) -> Self {
242		Self { runtime, windows }
243	}
244
245	/// Borrow the host windows without triggering device work.
246	pub fn windows(&self) -> &OhlcvWindows<'a> {
247		&self.windows
248	}
249}
250
251impl Dataset for OhlcvDataset<'_> {
252	fn len(&self) -> i64 {
253		self.windows.len()
254	}
255
256	fn get_item(&self, index: i64) -> Result<Matrix> {
257		let (input, _) = self.windows.window(index)?;
258		let mut values = Vec::new();
259		values
260			.try_reserve_exact(input.len() * 5)
261			.map_err(|_| Error::resource_exhausted("OHLCV feature packing allocation failed"))?;
262		for row in 0..input.len() {
263			for column in input.columns {
264				let value = column.float_at(row).expect("validated float column") as f32;
265				if !value.is_finite() {
266					return Err(Error::invalid_argument("OHLCV value exceeds FP32 range"));
267				}
268				values.push(value);
269			}
270		}
271		Matrix::new_from_slice_on(self.runtime, vec![input.len(), 5], &values)
272	}
273
274	fn get_sample(&self, index: i64) -> Result<Sample> {
275		let (_, future) = self.windows.window(index)?;
276		let mut labels = Vec::new();
277		labels
278			.try_reserve_exact(future.len())
279			.map_err(|_| Error::resource_exhausted("OHLCV label packing allocation failed"))?;
280		for row in 0..future.len() {
281			let value = future.columns[3]
282				.float_at(row)
283				.expect("validated close column") as f32;
284			if !value.is_finite() {
285				return Err(Error::invalid_argument("OHLCV close exceeds FP32 range"));
286			}
287			labels.push(value);
288		}
289		let x = self.get_item(index)?;
290		let y = Matrix::new_from_slice_on(self.runtime, vec![future.len()], &labels)?;
291		Ok(Sample::new_with_label(x, y))
292	}
293}