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        #[serde(alias = "calculate_operating_income_yoy_growth_ratio")]
111        OperatingIncomeYoyGrowthRatio => "operating_income_yoy_growth_ratio",
112        #[serde(alias = "calculate_operating_profit_yoy_growth_ratio")]
113        OperatingProfitYoyGrowthRatio => "operating_profit_yoy_growth_ratio",
114        FixedAssetInvestExpansionRatio => "fixed_asset_invest_expansion_ratio",
115        #[serde(alias = "calculate_parent_holder_net_profit_yoy_growth_ratio")]
116        ParentHolderNetProfitYoyGrowthRatio => "parent_holder_net_profit_yoy_growth_ratio",
117        SaleGrossMargin => "sale_gross_margin",
118        SaleNetInterestRatio => "sale_net_interest_ratio",
119        TotalAssetsNetRatio => "total_assets_net_ratio",
120        DeductWeightedAverageReturnOnEquity => "index_deduct_weighted_avg_roe",
121        WeightedAverageReturnOnEquity => "index_weighted_avg_roe",
122        CurrentRatio => "current_ratio",
123        QuickRatio => "quick_ratio",
124        AssetsDebtRatio => "assets_debt_ratio",
125        CashRatio => "cash_ratio",
126        EarnedInterestMultiple => "earned_interest_multiple",
127        LongTermDebtEquityRatio => "long_term_debt_equity_ratio",
128        TotalAssetsTurnoverRatio => "total_assets_turnover_ratio",
129        InventoryTurnoverRatio => "inventory_turnover_ratio",
130        CurrentAssetsTurnoverRatio => "current_assets_turnover_ratio",
131        ReceiveAccountTurnoverRatio => "receive_account_turnover_ratio",
132        CashOperatingIndex => "cash_operating_index",
133        OperatingCashFlowNetDivideIncome => "operating_cash_flow_net_divide_income",
134        NetProfitCashContent => "net_profit_cash_content",
135        OperatingCashNetYoyGrowthRatio => "operating_cash_net_yoy_growth_ratio",
136        CashMeetInvestRatio => "cash_meet_invest_ratio",
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::{FinancialRange, FinancialReport};
143    use crate::UnixMillis;
144
145    #[test]
146    fn financial_range_makes_conflicting_modes_unrepresentable() {
147        assert!(FinancialRange::recent(1).is_ok());
148        assert!(FinancialRange::recent(20).is_ok());
149        assert!(FinancialRange::recent(0).is_err());
150        assert!(FinancialRange::recent(21).is_err());
151
152        let start = UnixMillis::new(1_700_000_000_000).unwrap();
153        let end = UnixMillis::new(1_600_000_000_000).unwrap();
154        assert!(FinancialRange::between(start, end).is_err());
155    }
156
157    #[test]
158    fn financial_report_uses_standard_fallible_conversion() {
159        let report: FinancialReport = "2024-4".parse().unwrap();
160
161        assert_eq!(report.as_str(), "2024-4");
162        assert!("2024-5".parse::<FinancialReport>().is_err());
163    }
164}