Skip to main content

financial_api/a_share/
special_data.rs

1use serde::de::DeserializeOwned;
2
3use crate::endpoints;
4use crate::endpoints::join_values;
5use crate::{
6    AShareCode, AnomalyData, AnomalyTag, Client, DragonTigerBoard, DragonTigerData, Error,
7    HotListPeriod, HotStockData, HotStockHistoryData, HotStockTrendData, LadderData,
8    LimitBreakData, LimitBreakSortField, LimitDownData, LimitDownSortField, LimitUpData,
9    LimitUpSortField, NaturalDate, Page, Response, ShanghaiDateMillis, SortDirection,
10    ValidationError,
11};
12
13use super::validate_date_order;
14
15impl Client {
16    /// Fetch today's anomaly rows, optionally filtered with OR-combined tags.
17    pub async fn special_data_anomaly_analysis_list(
18        &self,
19        tag_codes: &[AnomalyTag],
20    ) -> Result<Response<AnomalyData>, Error> {
21        let query = if tag_codes.is_empty() {
22            Vec::new()
23        } else {
24            vec![("tag_codes", join_values("tag_codes", tag_codes, None)?)]
25        };
26        self.get(endpoints::ANOMALY_LIST, &query).await
27    }
28
29    /// Fetch today's anomaly rows for up to 50 A-share targets.
30    pub async fn special_data_anomaly_analysis_stock(
31        &self,
32        thscodes: &[AShareCode],
33    ) -> Result<Response<AnomalyData>, Error> {
34        let query = [("thscodes", join_values("thscodes", thscodes, Some(50))?)];
35        self.get(endpoints::ANOMALY_STOCK, &query).await
36    }
37
38    /// Fetch the dragon-tiger list.
39    pub async fn special_data_dragon_tiger_list(
40        &self,
41        board_type: DragonTigerBoard,
42        date: Option<NaturalDate>,
43    ) -> Result<Response<DragonTigerData>, Error> {
44        if let Some(date) = date {
45            self.validate_recent_date(date, "date")?;
46        }
47        let mut query = vec![("board_type", board_type.to_string())];
48        if let Some(date) = date {
49            query.push(("date", date.to_string()));
50        }
51        self.get(endpoints::DRAGON_TIGER, &query).await
52    }
53
54    /// Fetch the current hot-stock list.
55    pub async fn special_data_hot_stock_list(
56        &self,
57        period: HotListPeriod,
58    ) -> Result<Response<HotStockData>, Error> {
59        self.get(endpoints::HOT_STOCK_LIST, &[("period", period.to_string())])
60            .await
61    }
62
63    /// Fetch a historical hot-stock ranking for one natural day.
64    pub async fn special_data_hot_stock_list_history(
65        &self,
66        date: NaturalDate,
67    ) -> Result<Response<HotStockHistoryData>, Error> {
68        self.validate_recent_date(date, "date")?;
69        self.get(endpoints::HOT_STOCK_HISTORY, &[("date", date.to_string())])
70            .await
71    }
72
73    /// Fetch one A-share target's hot-rank trend.
74    pub async fn special_data_hot_stock_rank_trend(
75        &self,
76        thscode: &AShareCode,
77        start_date: NaturalDate,
78        end_date: NaturalDate,
79    ) -> Result<Response<HotStockTrendData>, Error> {
80        validate_date_order(start_date, end_date, "end_date")?;
81        self.validate_recent_date(start_date, "start_date")?;
82        self.validate_recent_date(end_date, "end_date")?;
83        if start_date
84            .checked_add_years(1)
85            .is_none_or(|limit| end_date > limit)
86        {
87            return Err(
88                ValidationError::new("end_date", "date range must not exceed one year").into(),
89            );
90        }
91        let query = [
92            ("thscode", thscode.to_string()),
93            ("start_date", start_date.to_string()),
94            ("end_date", end_date.to_string()),
95        ];
96        self.get(endpoints::HOT_STOCK_TREND, &query).await
97    }
98
99    /// Fetch the limit-up pool.
100    pub async fn special_data_limit_up_pool(
101        &self,
102        date_ms: Option<ShanghaiDateMillis>,
103        page: Page,
104        sort_field: LimitUpSortField,
105        sort_dir: SortDirection,
106    ) -> Result<Response<LimitUpData>, Error> {
107        self.special_data_pool(
108            endpoints::LIMIT_UP_POOL,
109            date_ms,
110            page,
111            sort_field.to_string(),
112            sort_dir,
113        )
114        .await
115    }
116
117    /// Fetch the limit-down pool.
118    pub async fn special_data_limit_down_pool(
119        &self,
120        date_ms: Option<ShanghaiDateMillis>,
121        page: Page,
122        sort_field: LimitDownSortField,
123        sort_dir: SortDirection,
124    ) -> Result<Response<LimitDownData>, Error> {
125        self.special_data_pool(
126            endpoints::LIMIT_DOWN_POOL,
127            date_ms,
128            page,
129            sort_field.to_string(),
130            sort_dir,
131        )
132        .await
133    }
134
135    /// Fetch the limit-break pool.
136    pub async fn special_data_limit_break_pool(
137        &self,
138        date_ms: Option<ShanghaiDateMillis>,
139        page: Page,
140        sort_field: LimitBreakSortField,
141        sort_dir: SortDirection,
142    ) -> Result<Response<LimitBreakData>, Error> {
143        self.special_data_pool(
144            endpoints::LIMIT_BREAK_POOL,
145            date_ms,
146            page,
147            sort_field.to_string(),
148            sort_dir,
149        )
150        .await
151    }
152
153    async fn special_data_pool<T: DeserializeOwned>(
154        &self,
155        path: &str,
156        date_ms: Option<ShanghaiDateMillis>,
157        page: Page,
158        sort_field: String,
159        sort_dir: SortDirection,
160    ) -> Result<Response<T>, Error> {
161        let mut query = vec![
162            ("page", page.number().to_string()),
163            ("size", page.size().to_string()),
164            ("sort_field", sort_field),
165            ("sort_dir", sort_dir.to_string()),
166        ];
167        if let Some(date_ms) = date_ms {
168            query.push(("date_ms", date_ms.to_string()));
169        }
170        self.get(path, &query).await
171    }
172
173    fn validate_recent_date(
174        &self,
175        date: NaturalDate,
176        field: &'static str,
177    ) -> Result<(), ValidationError> {
178        let today = self.shanghai_today();
179        let earliest = today
180            .checked_add_years(-1)
181            .ok_or_else(|| ValidationError::new(field, "could not calculate one-year window"))?;
182        if date < earliest || date > today {
183            return Err(ValidationError::new(
184                field,
185                "must be within the previous natural year and not in the future",
186            ));
187        }
188        Ok(())
189    }
190
191    /// Fetch the fixed 30-trading-day limit-up ladder.
192    pub async fn special_data_limit_up_ladder(&self) -> Result<Response<LadderData>, Error> {
193        self.get(endpoints::LIMIT_UP_LADDER, &[] as &[(&str, &str)])
194            .await
195    }
196
197    /// Fetch the current skyrocket ranking.
198    pub async fn special_data_skyrocket_list(
199        &self,
200        period: HotListPeriod,
201    ) -> Result<Response<HotStockData>, Error> {
202        self.get(endpoints::SKYROCKET_LIST, &[("period", period.to_string())])
203            .await
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use crate::ApiKey;
211
212    fn client() -> Client {
213        Client::builder(ApiKey::new("test-api-key").unwrap())
214            .base_url("http://127.0.0.1:9")
215            .reference_date(NaturalDate::parse("2026-08-25").unwrap())
216            .build()
217            .unwrap()
218    }
219
220    #[tokio::test]
221    async fn stock_analysis_rejects_more_than_fifty_targets_before_transport() {
222        let stock = AShareCode::new("600519.SH").unwrap();
223
224        let error = client()
225            .special_data_anomaly_analysis_stock(&vec![stock; 51])
226            .await
227            .unwrap_err();
228
229        assert!(matches!(error, Error::InvalidInput(_)));
230    }
231
232    #[tokio::test]
233    async fn recent_date_capabilities_enforce_their_documented_windows() {
234        let client = client();
235        let stock = AShareCode::new("600519.SH").unwrap();
236
237        for error in [
238            client
239                .special_data_hot_stock_rank_trend(
240                    &stock,
241                    NaturalDate::parse("2024-02-29").unwrap(),
242                    NaturalDate::parse("2025-03-01").unwrap(),
243                )
244                .await
245                .unwrap_err(),
246            client
247                .special_data_hot_stock_list_history(NaturalDate::parse("2025-08-24").unwrap())
248                .await
249                .unwrap_err(),
250            client
251                .special_data_dragon_tiger_list(
252                    DragonTigerBoard::All,
253                    Some(NaturalDate::parse("2026-08-26").unwrap()),
254                )
255                .await
256                .unwrap_err(),
257        ] {
258            assert!(matches!(error, Error::InvalidInput(_)));
259        }
260    }
261}