Skip to main content

financial_api/types/
finance.rs

1use std::str::FromStr;
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5use super::market_time::UnixMillis;
6use super::wire::wire_enum;
7use crate::ValidationError;
8
9/// Mutually exclusive recent-period or timestamp-range financial query.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum FinancialRange {
12    Recent { limit: u8 },
13    Between { start: UnixMillis, end: UnixMillis },
14}
15
16impl FinancialRange {
17    pub const fn recent(limit: u8) -> Result<Self, ValidationError> {
18        if limit == 0 || limit > 20 {
19            return Err(ValidationError::new("limit", "must be in the range 1..=20"));
20        }
21        Ok(Self::Recent { limit })
22    }
23
24    pub const fn between(start: UnixMillis, end: UnixMillis) -> Result<Self, ValidationError> {
25        if end.get() < start.get() {
26            return Err(ValidationError::new(
27                "end",
28                "must not be earlier than start",
29            ));
30        }
31        Ok(Self::Between { start, end })
32    }
33}
34
35/// Financial report identifier in `YYYY-[1-4]` form.
36#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
37#[serde(transparent)]
38pub struct FinancialReport(String);
39
40impl FinancialReport {
41    pub fn parse(value: impl Into<String>) -> Result<Self, ValidationError> {
42        let value = value.into();
43        let bytes = value.as_bytes();
44        let valid = bytes.len() == 6
45            && bytes[..4].iter().all(u8::is_ascii_digit)
46            && bytes[4] == b'-'
47            && matches!(bytes[5], b'1'..=b'4');
48        if !valid {
49            return Err(ValidationError::new("report", "must use YYYY-[1-4] format"));
50        }
51        Ok(Self(value))
52    }
53
54    #[must_use]
55    pub fn as_str(&self) -> &str {
56        &self.0
57    }
58}
59
60impl FromStr for FinancialReport {
61    type Err = ValidationError;
62
63    fn from_str(value: &str) -> Result<Self, Self::Err> {
64        Self::parse(value)
65    }
66}
67
68impl<'de> Deserialize<'de> for FinancialReport {
69    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
70        let value = String::deserialize(deserializer)?;
71        Self::parse(value).map_err(serde::de::Error::custom)
72    }
73}
74
75wire_enum! {
76    /// Financial statement report frequency.
77    pub enum FinancialPeriod {
78        Annual => "annual",
79        Quarterly => "quarterly",
80    }
81}
82
83wire_enum! {
84    /// Fiscal period returned by listed-company financial statements.
85    pub enum FiscalPeriod {
86        FullYear => "FY",
87        FirstQuarter => "Q1",
88        SecondQuarter => "Q2",
89        ThirdQuarter => "Q3",
90        FourthQuarter => "Q4",
91    }
92}
93
94wire_enum! {
95    /// Fixed financial-analysis ability group.
96    pub enum FinancialAbilityKind {
97        Growth => "growth",
98        Profitability => "profitability",
99        Solvency => "solvency",
100        Operation => "operation",
101        CashFlow => "cash-flow",
102    }
103}
104
105wire_enum! {
106    /// Financial indicator identifier defined by the upstream contract.
107    pub enum FinancialIndicatorId {
108        TotalAssetsGrowthRatio => "total_assets_growth_ratio",
109        NetProfitYoyGrowthRatio => "net_profit_yoy_growth_ratio",
110        OperatingIncomeYoyGrowthRatio => "operating_income_yoy_growth_ratio",
111        OperatingProfitYoyGrowthRatio => "operating_profit_yoy_growth_ratio",
112        SaleGrossMargin => "sale_gross_margin",
113        SaleNetInterestRatio => "sale_net_interest_ratio",
114        TotalAssetsNetRatio => "total_assets_net_ratio",
115        DeductWeightedAverageReturnOnEquity => "index_deduct_weighted_avg_roe",
116        WeightedAverageReturnOnEquity => "index_weighted_avg_roe",
117        CurrentRatio => "current_ratio",
118        QuickRatio => "quick_ratio",
119        AssetsDebtRatio => "assets_debt_ratio",
120        CashRatio => "cash_ratio",
121        EarnedInterestMultiple => "earned_interest_multiple",
122        LongTermDebtEquityRatio => "long_term_debt_equity_ratio",
123        TotalAssetsTurnoverRatio => "total_assets_turnover_ratio",
124        InventoryTurnoverRatio => "inventory_turnover_ratio",
125        CurrentAssetsTurnoverRatio => "current_assets_turnover_ratio",
126        ReceiveAccountTurnoverRatio => "receive_account_turnover_ratio",
127        CashOperatingIndex => "cash_operating_index",
128        OperatingCashFlowNetDivideIncome => "operating_cash_flow_net_divide_income",
129        NetProfitCashContent => "net_profit_cash_content",
130        OperatingCashNetYoyGrowthRatio => "operating_cash_net_yoy_growth_ratio",
131        CashMeetInvestRatio => "cash_meet_invest_ratio",
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::{FinancialRange, FinancialReport};
138    use crate::UnixMillis;
139
140    #[test]
141    fn financial_range_makes_conflicting_modes_unrepresentable() {
142        assert!(FinancialRange::recent(1).is_ok());
143        assert!(FinancialRange::recent(20).is_ok());
144        assert!(FinancialRange::recent(0).is_err());
145        assert!(FinancialRange::recent(21).is_err());
146
147        let start = UnixMillis::new(1_700_000_000_000).unwrap();
148        let end = UnixMillis::new(1_600_000_000_000).unwrap();
149        assert!(FinancialRange::between(start, end).is_err());
150    }
151
152    #[test]
153    fn financial_report_uses_standard_fallible_conversion() {
154        let report: FinancialReport = "2024-4".parse().unwrap();
155
156        assert_eq!(report.as_str(), "2024-4");
157        assert!("2024-5".parse::<FinancialReport>().is_err());
158    }
159}