Skip to main content

Series

Struct Series 

Source
pub struct Series<'a> { /* private fields */ }
Expand description

A view over contiguous observations, oldest first.

Besides the values, a series knows its seasonal period (12 for monthly data with a yearly cycle, 4 for quarterly, 1 for none) and where it sits in the original data: slicing keeps the absolute position, so the season of each observation and the alignment with external data (a price index, a regressor) survive any head, tail or slice.

Implementations§

Source§

impl<'a> Series<'a>

Source

pub fn new(values: &'a [f64], period: usize) -> Self

A series with the given seasonal period (0 is read as 1: no seasonality). The first observation is taken to be at season 0; see with_phase.

Source

pub fn non_seasonal(values: &'a [f64]) -> Self

A series without seasonality.

Source

pub fn monthly(values: &'a [f64], first_month: usize) -> Self

Monthly data with a yearly cycle; first_month is the calendar month of the first observation, 0 = January.

Examples found in repository?
examples/piaui.rs (line 20)
9fn main() {
10    let data = include_str!("../data/piaui_revenue.csv");
11    let rows: Vec<Vec<f64>> = data
12        .lines()
13        .filter(|l| !l.starts_with('#') && !l.starts_with("month"))
14        .map(|l| l.split(',').skip(1).map(|v| v.parse().unwrap()).collect())
15        .collect();
16
17    for (column, name) in [(0, "ICMS"), (1, "FPE")] {
18        let values: Vec<f64> = rows.iter().map(|r| r[column]).collect();
19        // the first observation is March 2017
20        let y = Series::monthly(&values, 2);
21        let report = Backtest::default()
22            .run(y, &models::thorough())
23            .expect("series long enough");
24
25        println!(
26            "\n{name}: {} origins, {} months ahead",
27            report.origins, report.horizon
28        );
29        let mut ranking: Vec<_> = report.candidates.iter().collect();
30        ranking.sort_by(|a, b| a.score.total_cmp(&b.score));
31        for c in ranking {
32            let h = |i: usize| c.horizons[i].mape.unwrap_or(f64::NAN);
33            println!(
34                "  {:<45} MAPE {:5.2}%   h=1 {:5.2}%   h=12 {:5.2}%",
35                c.name,
36                c.score,
37                h(0),
38                h(11)
39            );
40        }
41        let best = report.chosen();
42        let half = best.cumulative(6).expect("six months");
43        let i = half.interval(0.80).expect("80% interval");
44        println!(
45            "  next 6 months with {}: {:.2} bi (80%: {:.2} to {:.2})",
46            best.name,
47            half.mean / 1e9,
48            i.lower / 1e9,
49            i.upper / 1e9
50        );
51    }
52}
Source

pub fn quarterly(values: &'a [f64], first_quarter: usize) -> Self

Quarterly data with a yearly cycle; first_quarter is 0 for Q1.

Source

pub fn with_phase(self, phase: usize) -> Self

Sets the season of the first observation of this view.

Source

pub fn values(&self) -> &'a [f64]

Source

pub fn len(&self) -> usize

Source

pub fn is_empty(&self) -> bool

Source

pub fn period(&self) -> usize

Source

pub fn start(&self) -> usize

Absolute index, in the original data, of the first observation.

Source

pub fn index(&self, i: usize) -> usize

Absolute index of observation i. i may be past the end: len() is the first period to be forecast.

Source

pub fn season(&self, i: usize) -> usize

Season (0..period) of observation i; like index, i may be past the end.

Source

pub fn head(&self, n: usize) -> Self

The first n observations (all of them if n is larger).

Source

pub fn tail(&self, n: usize) -> Self

The last n observations (all of them if n is larger).

Source

pub fn slice(&self, range: Range<usize>) -> Self

Observations in range, clamped to the series.

Source

pub fn with_values<'b>(&self, values: &'b [f64]) -> Option<Series<'b>>

The same series (period, season and position) over other values, such as a transformation of the original ones. None if the lengths differ.

Source

pub fn is_finite(&self) -> bool

True when every value is finite.

Source

pub fn is_positive(&self) -> bool

True when every value is finite and greater than zero (what multiplicative and logarithmic models need).

Trait Implementations§

Source§

impl<'a> Clone for Series<'a>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Copy for Series<'a>

Source§

impl<'a> Debug for Series<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> PartialEq for Series<'a>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<'a> StructuralPartialEq for Series<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Series<'a>

§

impl<'a> RefUnwindSafe for Series<'a>

§

impl<'a> Send for Series<'a>

§

impl<'a> Sync for Series<'a>

§

impl<'a> Unpin for Series<'a>

§

impl<'a> UnsafeUnpin for Series<'a>

§

impl<'a> UnwindSafe for Series<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.