tickbar 0.1.0

High-performance tick-to-bar aggregator for market data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use smol_str::SmolStr;
use std::io::Write;

/// A single OHLCV bar — 48 bytes.
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct Bar {
    /// Bar start time (UTC nanoseconds).
    pub timestamp_nanos: i64,
    /// Open price.
    pub open: i64,
    /// High price.
    pub high: i64,
    /// Low price.
    pub low: i64,
    /// Close price.
    pub close: i64,
    /// Total volume.
    pub volume: i64,
    /// Number of ticks in this bar.
    pub tick_count: u32,
    /// Volume-weighted average price.
    pub vwap: i64,
}

/// A time-ordered series of bars for a single symbol.
pub struct BarSeries {
    pub(crate) bars: Vec<Bar>,
    symbol: SmolStr,
    interval_nanos: i64,
    _price_scale: u8,
    _volume_scale: u8,
    timezone_offset: i32,
}

impl BarSeries {
    /// Create a new `BarSeries`.
    pub fn new(symbol: impl Into<SmolStr>, interval_nanos: i64) -> Self {
        BarSeries {
            bars: Vec::new(),
            symbol: symbol.into(),
            interval_nanos,
            _price_scale: 8,
            _volume_scale: 0,
            timezone_offset: 0,
        }
    }

    /// Return a reference to the underlying bars.
    pub fn as_slice(&self) -> &[Bar] {
        &self.bars
    }

    /// Return a mutable reference to the underlying bars.
    pub fn bars_mut(&mut self) -> &mut Vec<Bar> {
        &mut self.bars
    }

    /// Consume the series and return the inner bar vector.
    pub fn into_inner(self) -> Vec<Bar> {
        self.bars
    }

    /// Push a completed bar onto the series.
    pub fn push(&mut self, bar: Bar) {
        self.bars.push(bar);
    }

    /// Return the symbol for this series.
    pub fn symbol(&self) -> &SmolStr {
        &self.symbol
    }

    /// Return the bar interval in nanoseconds.
    pub fn interval_nanos(&self) -> i64 {
        self.interval_nanos
    }

    /// Set the timezone offset (seconds from UTC).
    pub fn with_timezone_offset(mut self, offset: i32) -> Self {
        self.timezone_offset = offset;
        self
    }

    /// Export bars to Arrow `RecordBatch` (zero-copy).
    #[cfg(feature = "arrow-export")]
    pub fn to_arrow(&self) -> Result<arrow::record_batch::RecordBatch, arrow::error::ArrowError> {
        use arrow::array::{Int64Array, UInt32Array};
        use arrow::datatypes::{DataType, Field, Schema};
        use std::sync::Arc;
        let schema = Arc::new(Schema::new(vec![
            Field::new("timestamp_nanos", DataType::Int64, false),
            Field::new("open", DataType::Int64, false),
            Field::new("high", DataType::Int64, false),
            Field::new("low", DataType::Int64, false),
            Field::new("close", DataType::Int64, false),
            Field::new("volume", DataType::Int64, false),
            Field::new("tick_count", DataType::UInt32, false),
            Field::new("vwap", DataType::Int64, false),
        ]));
        let n = self.bars.len();
        let cap = n.max(1);
        let mut ts = Vec::with_capacity(cap);
        let mut open = Vec::with_capacity(cap);
        let mut high = Vec::with_capacity(cap);
        let mut low = Vec::with_capacity(cap);
        let mut close = Vec::with_capacity(cap);
        let mut volume = Vec::with_capacity(cap);
        let mut tick_count = Vec::with_capacity(cap);
        let mut vwap = Vec::with_capacity(cap);
        for bar in &self.bars {
            ts.push(bar.timestamp_nanos);
            open.push(bar.open);
            high.push(bar.high);
            low.push(bar.low);
            close.push(bar.close);
            volume.push(bar.volume);
            tick_count.push(bar.tick_count);
            vwap.push(bar.vwap);
        }
        let columns: Vec<arrow::array::ArrayRef> = vec![
            Arc::new(Int64Array::from(ts)),
            Arc::new(Int64Array::from(open)),
            Arc::new(Int64Array::from(high)),
            Arc::new(Int64Array::from(low)),
            Arc::new(Int64Array::from(close)),
            Arc::new(Int64Array::from(volume)),
            Arc::new(UInt32Array::from(tick_count)),
            Arc::new(Int64Array::from(vwap)),
        ];
        let batch = arrow::record_batch::RecordBatch::try_new(schema, columns)?;
        Ok(batch)
    }

    /// Export bars to a Polars `DataFrame`.
    #[cfg(feature = "polars-export")]
    pub fn to_polars(&self) -> polars::prelude::PolarsResult<polars::frame::DataFrame> {
        use polars::prelude::*;
        let ts: Vec<i64> = self.bars.iter().map(|b| b.timestamp_nanos).collect();
        let open: Vec<i64> = self.bars.iter().map(|b| b.open).collect();
        let high: Vec<i64> = self.bars.iter().map(|b| b.high).collect();
        let low: Vec<i64> = self.bars.iter().map(|b| b.low).collect();
        let close: Vec<i64> = self.bars.iter().map(|b| b.close).collect();
        let volume: Vec<i64> = self.bars.iter().map(|b| b.volume).collect();
        let tick_count: Vec<u32> = self.bars.iter().map(|b| b.tick_count).collect();
        let vwap: Vec<i64> = self.bars.iter().map(|b| b.vwap).collect();
        let cols = vec![
            Column::new("timestamp_nanos".into(), ts),
            Column::new("open".into(), open),
            Column::new("high".into(), high),
            Column::new("low".into(), low),
            Column::new("close".into(), close),
            Column::new("volume".into(), volume),
            Column::new("tick_count".into(), tick_count),
            Column::new("vwap".into(), vwap),
        ];
        DataFrame::new(self.bars.len(), cols)
    }

    /// Export bars to CSV format.
    ///
    /// Writes CSV rows: timestamp_nanos,open,high,low,close,volume,tick_count,vwap
    pub fn to_csv<W: Write>(&self, writer: &mut csv::Writer<W>) -> Result<(), csv::Error> {
        for bar in &self.bars {
            writer.serialize((
                bar.timestamp_nanos,
                bar.open,
                bar.high,
                bar.low,
                bar.close,
                bar.volume,
                bar.tick_count,
                bar.vwap,
            ))?;
        }
        writer.flush()?;
        Ok(())
    }

    /// Resample bars to a new (larger) interval.
    ///
    /// The new interval must be an integer multiple of the current interval.
    /// Returns `InvalidConfiguration` if the new interval is not a multiple.
    pub fn resample(&self, new_interval_nanos: i64) -> Result<BarSeries, crate::Error> {
        if new_interval_nanos % self.interval_nanos != 0 {
            return Err(crate::Error::InvalidConfiguration(
                "new interval must be a multiple of the current interval".into(),
            ));
        }
        let factor = (new_interval_nanos / self.interval_nanos) as usize;
        let mut out = BarSeries::new(self.symbol.clone(), new_interval_nanos);

        let mut i = 0;
        while i < self.bars.len() {
            let chunk_end = (i + factor).min(self.bars.len());
            let first = &self.bars[i];

            let mut high = first.high;
            let mut low = first.low;
            let mut volume = first.volume;
            let mut tick_count = first.tick_count;
            let mut vwap_num = first.vwap * first.volume;

            let last_idx = chunk_end - 1;
            for j in (i + 1)..chunk_end {
                let b = &self.bars[j];
                if b.high > high {
                    high = b.high;
                }
                if b.low < low {
                    low = b.low;
                }
                volume += b.volume;
                tick_count += b.tick_count;
                vwap_num += b.vwap * b.volume;
            }

            let last = &self.bars[last_idx];
            let vwap = if volume > 0 {
                vwap_num / volume
            } else {
                last.close
            };

            out.push(Bar {
                timestamp_nanos: first.timestamp_nanos,
                open: first.open,
                high,
                low,
                close: last.close,
                volume,
                tick_count,
                vwap,
            });

            i = chunk_end;
        }
        Ok(out)
    }
}

/// Mutable builder for constructing a `Bar` from incoming ticks.
#[derive(Debug)]
pub struct BarBuilder {
    /// Bar start time.
    pub start_time: i64,
    /// Bar end time (exclusive).
    pub end_time: i64,
    /// First tick price.
    pub open: Option<i64>,
    /// Max price.
    pub high: i64,
    /// Min price.
    pub low: i64,
    /// Last tick price.
    pub close: i64,
    /// Sum of volume.
    pub volume_sum: i64,
    /// Sum(price * volume).
    pub vwap_numerator: i64,
    /// Number of ticks.
    pub tick_count: u32,
}

impl BarBuilder {
    /// Create a new `BarBuilder` for the interval `[start, end)`.
    pub fn new(start_time: i64, end_time: i64) -> Self {
        BarBuilder {
            start_time,
            end_time,
            open: None,
            high: i64::MIN,
            low: i64::MAX,
            close: 0,
            volume_sum: 0,
            vwap_numerator: 0,
            tick_count: 0,
        }
    }

    /// Update the bar with a new tick's price and volume.
    #[inline(always)]
    pub fn update(&mut self, price: i64, volume: i64) {
        if self.open.is_none() {
            self.open = Some(price);
        }
        self.high = self.high.max(price);
        self.low = self.low.min(price);
        self.close = price;
        self.volume_sum += volume;
        self.vwap_numerator += price * volume;
        self.tick_count += 1;
    }

    /// Build the final `Bar`.
    pub fn build(&self) -> Bar {
        let open = self.open.unwrap_or(self.close);
        Bar {
            timestamp_nanos: self.start_time,
            open,
            high: self.high,
            low: self.low,
            close: self.close,
            volume: self.volume_sum,
            tick_count: self.tick_count,
            vwap: if self.volume_sum > 0 {
                self.vwap_numerator / self.volume_sum
            } else {
                self.close
            },
        }
    }

    /// Returns `true` if this builder has received at least one tick.
    pub fn is_empty(&self) -> bool {
        self.tick_count == 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bar_builder_basic() {
        let mut b = BarBuilder::new(0, 60_000_000_000);
        b.update(100, 1000);
        b.update(200, 500);
        let bar = b.build();
        assert_eq!(bar.open, 100);
        assert_eq!(bar.high, 200);
        assert_eq!(bar.low, 100);
        assert_eq!(bar.close, 200);
        assert_eq!(bar.volume, 1500);
        assert_eq!(bar.tick_count, 2);
        assert_eq!(bar.vwap, (100 * 1000 + 200 * 500) / 1500);
    }

    #[test]
    fn test_bar_builder_empty() {
        let b = BarBuilder::new(0, 60_000_000_000);
        assert!(b.is_empty());
    }

    #[test]
    fn test_bar_builder_single_tick() {
        let mut b = BarBuilder::new(0, 60_000_000_000);
        b.update(150, 2000);
        let bar = b.build();
        assert_eq!(bar.open, 150);
        assert_eq!(bar.close, 150);
        assert_eq!(bar.high, 150);
        assert_eq!(bar.low, 150);
        assert_eq!(bar.vwap, 150);
    }

    #[test]
    fn test_bar_series_push_and_slice() {
        let mut s = BarSeries::new("AAPL", 60_000_000_000);
        assert_eq!(s.as_slice().len(), 0);
        let bar = Bar {
            timestamp_nanos: 0,
            open: 100,
            high: 110,
            low: 90,
            close: 105,
            volume: 5000,
            tick_count: 10,
            vwap: 102,
        };
        s.push(bar);
        assert_eq!(s.as_slice().len(), 1);
        assert_eq!(s.symbol(), "AAPL");
        assert_eq!(s.interval_nanos(), 60_000_000_000);
    }

    #[test]
    fn test_bar_series_resample() {
        let mut s = BarSeries::new("TEST", 60_000_000_000);
        for i in 0..4 {
            s.push(Bar {
                timestamp_nanos: i * 60_000_000_000,
                open: 100 + i,
                high: 110 + i,
                low: 90 + i,
                close: 105 + i,
                volume: 1000,
                tick_count: 5,
                vwap: 102 + i,
            });
        }
        let resampled = s.resample(120_000_000_000).unwrap();
        assert_eq!(resampled.as_slice().len(), 2);
        assert_eq!(resampled.as_slice()[0].open, 100);
        assert_eq!(resampled.as_slice()[0].close, 106);
        assert_eq!(resampled.as_slice()[0].volume, 2000);
        assert_eq!(resampled.as_slice()[0].tick_count, 10);
    }

    #[test]
    fn test_resample_invalid_interval() {
        let s = BarSeries::new("TEST", 60_000_000_000);
        let result = s.resample(90_000_000_000);
        assert!(result.is_err());
    }

    #[test]
    fn test_to_csv() {
        let mut s = BarSeries::new("TEST", 60_000_000_000);
        s.push(Bar {
            timestamp_nanos: 0,
            open: 100,
            high: 110,
            low: 90,
            close: 105,
            volume: 1000,
            tick_count: 5,
            vwap: 102,
        });
        let mut buf = Vec::new();
        let mut w = csv::Writer::from_writer(&mut buf);
        s.to_csv(&mut w).unwrap();
        drop(w);
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("100,110,90,105,1000,5,102"));
    }
}