1pub use super::types::OhlcvWindowConfig;
6use super::{DataFrame, DataFrameView, Dataset, Sample, SeriesView};
7use crate::{Engine, Error, Matrix, Result};
8use std::ops::Range;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum UnixTimeUnit {
13 Seconds,
15 Milliseconds,
17 Microseconds,
19 Nanoseconds,
21}
22
23#[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 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 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 pub fn timestamps(self) -> &'a [i64] {
97 self.timestamps
98 }
99
100 pub fn time_unit(self) -> UnixTimeUnit {
102 self.unit
103 }
104
105 pub fn columns(self) -> [SeriesView<'a>; 5] {
107 self.columns
108 }
109
110 pub fn len(self) -> usize {
112 self.timestamps.len()
113 }
114
115 pub fn is_empty(self) -> bool {
117 self.timestamps.is_empty()
118 }
119
120 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 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#[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 pub fn len(&self) -> i64 {
171 self.count
172 }
173
174 pub fn is_empty(&self) -> bool {
176 self.count == 0
177 }
178
179 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 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
228pub struct OhlcvDataset<'a> {
235 engine: &'a Engine,
236 windows: OhlcvWindows<'a>,
237}
238
239impl<'a> OhlcvDataset<'a> {
240 pub fn new(engine: &'a Engine, windows: OhlcvWindows<'a>) -> Self {
242 Self { engine, windows }
243 }
244
245 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.engine, 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.engine, vec![future.len()], &labels)?;
291 Ok(Sample::new_with_label(x, y))
292 }
293}