Skip to main content

ferric_fred/
regional_data.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::SeriesId;
6
7/// Regional economic data from GeoFRED / Maps — the shared response of both
8/// `geofred/series/data` (one series' values across regions, over time) and
9/// `geofred/regional/data` (a series group's cross-section at a date). The two
10/// endpoints return the **same** shape (ADR-0025), so one type serves both.
11///
12/// FRED nests everything under a single `meta` object; this type mirrors that.
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
15pub struct RegionalData {
16    /// The `meta` payload: the descriptive header plus the dated regional values.
17    pub meta: RegionalDataMeta,
18}
19
20/// The `meta` payload of a [`RegionalData`] response: a descriptive header and
21/// the values, keyed by date.
22///
23/// `title`, `region`, `seasonality`, `units`, and `frequency` are FRED **display
24/// labels** ("state", "Not Seasonally Adjusted", "Dollars", "Annual"), so they
25/// are kept as `String` rather than parsed into enums — the request side of the
26/// API uses codes, but these come back as free text (ADR-0025).
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
29pub struct RegionalDataMeta {
30    /// FRED's descriptive title for the result, e.g.
31    /// `"2025 Per Capita Personal Income by State (Dollars)"`.
32    pub title: String,
33
34    /// The region granularity as a display label, e.g. `"state"`.
35    pub region: String,
36
37    /// The seasonality as a display label, e.g. `"Not Seasonally Adjusted"`.
38    pub seasonality: String,
39
40    /// The units as a display label, e.g. `"Dollars"` — echoed from the request's
41    /// free-form `units` value (ADR-0025).
42    pub units: String,
43
44    /// The frequency as a display label, e.g. `"Annual"`.
45    pub frequency: String,
46
47    /// The regional values, keyed by observation date (`BTreeMap` for a
48    /// deterministic date order). Each date maps to one [`RegionalDataPoint`]
49    /// per region.
50    pub data: BTreeMap<String, Vec<RegionalDataPoint>>,
51}
52
53/// A single region's value within a [`RegionalDataMeta`] date bucket.
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
56pub struct RegionalDataPoint {
57    /// The region's display name, e.g. `"Alabama"`.
58    pub region: String,
59
60    /// FRED's region code, e.g. `"01"` for Alabama. A string because FRED zero-
61    /// pads it and uses non-numeric codes for some region types.
62    pub code: String,
63
64    /// The value for this region on this date. Unlike core FRED observations
65    /// (stringly-typed, `"."` for missing), GeoFRED sends a JSON number, so a
66    /// plain `Option<f64>` suffices — `None` for a `null` or absent value.
67    #[serde(default)]
68    pub value: Option<f64>,
69
70    /// The underlying FRED series this region's value comes from, e.g. `ALPCPI`.
71    pub series_id: SeriesId,
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    const REGIONAL_DATA: &str = r#"{
79        "meta": {
80            "title": "2025 Per Capita Personal Income by State (Dollars)",
81            "region": "state",
82            "seasonality": "Not Seasonally Adjusted",
83            "units": "Dollars",
84            "frequency": "Annual",
85            "data": {
86                "2013-01-01": [
87                    {"region": "Alabama", "code": "01", "value": 35706, "series_id": "ALPCPI"},
88                    {"region": "Alaska", "code": "02", "value": 54012.5, "series_id": "AKPCPI"}
89                ]
90            }
91        }
92    }"#;
93
94    #[test]
95    fn parses_meta_and_dated_points() {
96        let data: RegionalData = serde_json::from_str(REGIONAL_DATA).expect("regional data parses");
97        assert_eq!(data.meta.region, "state");
98        assert_eq!(data.meta.units, "Dollars");
99        let day = &data.meta.data["2013-01-01"];
100        assert_eq!(day.len(), 2);
101        assert_eq!(day[0].region, "Alabama");
102        assert_eq!(day[0].code, "01");
103        assert_eq!(day[0].value, Some(35706.0));
104        assert_eq!(day[0].series_id, SeriesId::new("ALPCPI"));
105        assert_eq!(day[1].value, Some(54012.5));
106    }
107
108    #[test]
109    fn missing_value_maps_to_none() {
110        let point: RegionalDataPoint = serde_json::from_str(
111            r#"{"region": "Nowhere", "code": "99", "value": null, "series_id": "NONE"}"#,
112        )
113        .expect("null value parses");
114        assert_eq!(point.value, None);
115    }
116}