Skip to main content

resample

Function resample 

Source
pub fn resample(
    bars: &[Bar],
    from: impl Into<BarClock>,
    to: impl Into<BarClock>,
) -> Option<Vec<Bar>>
Expand description

Builds bars of interval to from bars of interval from, which must be in time order. Pass timeframes for UTC boundaries, or BarClock values for a selected calendar timezone. Prices and volumes are expected to be finite, as stored series keep them.

Each output bar gathers the consecutive input bars that fall in one bar of the target BarClock and is stamped with that bar’s open time. It takes the open of the first input bar, the highest high, the lowest low, the close of the last input bar and the summed volume. A period without input bars has no output bar. When from == to, the bars are returned unchanged when the clocks also share a timezone.

Returns None when from bars do not nest in to bars: weekly and monthly bars into any other interval, or an input bar that would span two output bars, as a 5-minute bar opening at 00:05 does in 7-minute bars. Also returns None when the bars of one slot do not combine into a valid bar, as when their volumes add up to infinity.

use chrono::{DateTime, TimeDelta, Utc};
use egui_charts::data::{Bar, Timeframe, resample};

let start: DateTime<Utc> = "2024-03-15T10:00:00Z".parse().unwrap();
let minutes: Vec<Bar> = (0..10)
    .map(|i| {
        let price = 100.0 + i as f64;
        Bar::new(start + TimeDelta::minutes(i), price, price + 1.0, price - 1.0, price + 0.5, 10.0)
    })
    .collect();

let bars = resample(&minutes, Timeframe::Min1, Timeframe::Min5).unwrap();
assert_eq!(bars.len(), 2);
let last = &bars[1];
assert_eq!(last.time, start + TimeDelta::minutes(5));
assert_eq!(
    (last.open, last.high, last.low, last.close, last.volume),
    (105.0, 110.0, 104.0, 109.5, 50.0)
);