Skip to main content

financial_api/
fund.rs

1mod company;
2mod corporate_actions;
3mod diagnostics;
4mod financials;
5mod holders;
6mod managers;
7mod market;
8mod news;
9mod offerings;
10mod performance;
11mod portfolio;
12mod profile;
13
14use serde::de::DeserializeOwned;
15use time::OffsetDateTime;
16
17use crate::{Client, Error, FundType, Response, Thscode, UnixMillis, ValidationError};
18
19const HISTORY_YEARS: i32 = 5;
20const NANOS_PER_MILLISECOND: i128 = 1_000_000;
21
22impl Client {
23    async fn fund_detail<T: DeserializeOwned>(
24        &self,
25        path: &str,
26        fund_type: FundType,
27        thscode: impl TryInto<Thscode, Error: Into<ValidationError>>,
28    ) -> Result<Response<T>, Error> {
29        let query = fund_target_query(fund_type, thscode)?;
30        self.get(path, &query).await
31    }
32}
33
34fn fund_target_query(
35    fund_type: FundType,
36    thscode: impl TryInto<Thscode, Error: Into<ValidationError>>,
37) -> Result<Vec<(&'static str, String)>, ValidationError> {
38    let thscode: Thscode = thscode.try_into().map_err(Into::into)?;
39    let (_, suffix) = thscode.ticker_and_suffix();
40    let valid = match fund_type {
41        FundType::Otc => suffix == "OF",
42        FundType::Exchange | FundType::Reits => matches!(suffix, "SH" | "SZ"),
43    };
44    if !valid {
45        return Err(ValidationError::new(
46            "thscode",
47            "market suffix does not match fund_type",
48        ));
49    }
50    Ok(vec![
51        ("fund_type", fund_type.to_string()),
52        ("thscode", thscode.into_string()),
53    ])
54}
55
56fn validate_history_range(start: UnixMillis, end: UnixMillis) -> Result<(), ValidationError> {
57    if end < start {
58        return Err(ValidationError::new(
59            "end",
60            "must not be earlier than start",
61        ));
62    }
63
64    let start_datetime =
65        OffsetDateTime::from_unix_timestamp_nanos(i128::from(start.get()) * NANOS_PER_MILLISECOND)
66            .map_err(|_| {
67                ValidationError::new("start", "timestamp is outside the supported range")
68            })?;
69    let target_year = start_datetime
70        .year()
71        .checked_add(HISTORY_YEARS)
72        .ok_or_else(|| ValidationError::new("end", "timestamp year overflowed"))?;
73    let limit = start_datetime
74        .replace_year(target_year)
75        .or_else(|_| start_datetime.replace_day(28)?.replace_year(target_year))
76        .map_err(|_| ValidationError::new("end", "could not calculate the year limit"))?;
77    if i128::from(end.get()) * NANOS_PER_MILLISECOND > limit.unix_timestamp_nanos() {
78        return Err(ValidationError::new(
79            "end",
80            "requested time window exceeds the endpoint year limit",
81        ));
82    }
83    Ok(())
84}
85
86#[cfg(test)]
87mod tests {
88    use super::{fund_target_query, validate_history_range};
89    use crate::{FundType, Thscode, UnixMillis};
90
91    #[test]
92    fn fund_type_must_match_the_target_suffix() {
93        let otc = Thscode::new("025480.OF").unwrap();
94        let exchange = Thscode::new("510300.SH").unwrap();
95
96        assert!(fund_target_query(FundType::Otc, &otc).is_ok());
97        assert!(fund_target_query(FundType::Exchange, &exchange).is_ok());
98        assert!(fund_target_query(FundType::Reits, &exchange).is_ok());
99        assert!(fund_target_query(FundType::Otc, &exchange).is_err());
100        assert!(fund_target_query(FundType::Exchange, &otc).is_err());
101        assert!(fund_target_query(FundType::Reits, &otc).is_err());
102    }
103
104    #[test]
105    fn history_range_uses_calendar_years_at_a_leap_day_boundary() {
106        let start = UnixMillis::new(1_582_934_400_000).unwrap();
107        let five_year_limit = UnixMillis::new(1_740_700_800_000).unwrap();
108        let after_limit = UnixMillis::new(1_740_787_200_000).unwrap();
109
110        assert!(validate_history_range(start, five_year_limit).is_ok());
111        let error = validate_history_range(start, after_limit).unwrap_err();
112        assert_eq!(error.field(), "end");
113        assert_eq!(
114            error.problem(),
115            "requested time window exceeds the endpoint year limit"
116        );
117    }
118
119    #[test]
120    fn history_range_rejects_an_end_before_the_start() {
121        let start = UnixMillis::new(2).unwrap();
122        let end = UnixMillis::new(1).unwrap();
123
124        let error = validate_history_range(start, end).unwrap_err();
125
126        assert_eq!(error.field(), "end");
127        assert_eq!(error.problem(), "must not be earlier than start");
128    }
129}