Skip to main content

piaui/
piaui.rs

1//! Backtest of two public revenue series of the state of PiauĂ­, Brazil.
2//!
3//! ```text
4//! cargo run -p foresight --example piaui
5//! ```
6
7use foresight::{models, Backtest, Series};
8
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}