Skip to main content

financial_api/a_share/
special_data.rs

1use serde::de::DeserializeOwned;
2
3use crate::endpoints;
4use crate::endpoints::{join_a_share_codes, join_values};
5use crate::{
6    AnomalyData, AnomalyTag, Client, DragonTigerBoard, DragonTigerData, Error, HotListPeriod,
7    HotStockData, HotStockHistoryData, HotStockTrendData, LadderData, LimitBreakData,
8    LimitBreakSortField, LimitDownData, LimitDownSortField, LimitUpData, LimitUpSortField,
9    NaturalDate, Page, Response, ShanghaiDateMillis, SortDirection, ValidationError,
10};
11
12use super::validate_date_order;
13
14impl Client {
15    /// 获取当日异动分析记录,可按“或”关系组合标签筛选。
16    ///
17    /// # 示例
18    #[doc = concat!(
19        "```no_run\n",
20        include_str!("../../examples/special_data_anomaly_analysis_list.rs"),
21        "\n```"
22    )]
23    pub async fn special_data_anomaly_analysis_list(
24        &self,
25        tag_codes: &[AnomalyTag],
26    ) -> Result<Response<AnomalyData>, Error> {
27        let query = if tag_codes.is_empty() {
28            Vec::new()
29        } else {
30            vec![("tag_codes", join_values("tag_codes", tag_codes, None)?)]
31        };
32        self.get(endpoints::ANOMALY_LIST, &query).await
33    }
34
35    /// 获取最多 50 个 A 股标的的当日异动分析记录。
36    ///
37    /// # 示例
38    #[doc = concat!(
39        "```no_run\n",
40        include_str!("../../examples/special_data_anomaly_analysis_stock.rs"),
41        "\n```"
42    )]
43    pub async fn special_data_anomaly_analysis_stock(
44        &self,
45        thscodes: &[impl AsRef<str> + Sync],
46    ) -> Result<Response<AnomalyData>, Error> {
47        let query = [("thscodes", join_a_share_codes(thscodes, Some(50))?)];
48        self.get(endpoints::ANOMALY_STOCK, &query).await
49    }
50
51    /// 获取龙虎榜。
52    ///
53    /// # 示例
54    #[doc = concat!(
55        "```no_run\n",
56        include_str!("../../examples/special_data_dragon_tiger_list.rs"),
57        "\n```"
58    )]
59    pub async fn special_data_dragon_tiger_list(
60        &self,
61        board_type: DragonTigerBoard,
62        date: Option<&str>,
63    ) -> Result<Response<DragonTigerData>, Error> {
64        let date = date.map(NaturalDate::parse).transpose()?;
65        if let Some(date) = date {
66            self.validate_recent_date(date, "date")?;
67        }
68        let mut query = vec![("board_type", board_type.to_string())];
69        if let Some(date) = date {
70            query.push(("date", date.to_string()));
71        }
72        self.get(endpoints::DRAGON_TIGER, &query).await
73    }
74
75    /// 获取当前个股热榜。
76    ///
77    /// # 示例
78    #[doc = concat!(
79        "```no_run\n",
80        include_str!("../../examples/special_data_hot_stock_list.rs"),
81        "\n```"
82    )]
83    pub async fn special_data_hot_stock_list(
84        &self,
85        period: HotListPeriod,
86    ) -> Result<Response<HotStockData>, Error> {
87        self.get(endpoints::HOT_STOCK_LIST, &[("period", period.to_string())])
88            .await
89    }
90
91    /// 获取指定自然日的历史个股热榜。
92    ///
93    /// # 示例
94    #[doc = concat!(
95        "```no_run\n",
96        include_str!("../../examples/special_data_hot_stock_list_history.rs"),
97        "\n```"
98    )]
99    pub async fn special_data_hot_stock_list_history(
100        &self,
101        date: &str,
102    ) -> Result<Response<HotStockHistoryData>, Error> {
103        let date = NaturalDate::parse(date)?;
104        self.validate_recent_date(date, "date")?;
105        self.get(endpoints::HOT_STOCK_HISTORY, &[("date", date.to_string())])
106            .await
107    }
108
109    /// 获取指定 A 股标的的热榜排名趋势。
110    ///
111    /// # 示例
112    #[doc = concat!(
113        "```no_run\n",
114        include_str!("../../examples/special_data_hot_stock_rank_trend.rs"),
115        "\n```"
116    )]
117    pub async fn special_data_hot_stock_rank_trend(
118        &self,
119        thscode: impl AsRef<str> + Send,
120        start_date: &str,
121        end_date: &str,
122    ) -> Result<Response<HotStockTrendData>, Error> {
123        let thscode = crate::AShareCode::new(thscode)?;
124        let start_date = NaturalDate::parse(start_date)?;
125        let end_date = NaturalDate::parse(end_date)?;
126        validate_date_order(start_date, end_date, "end_date")?;
127        self.validate_recent_date(start_date, "start_date")?;
128        self.validate_recent_date(end_date, "end_date")?;
129        if start_date
130            .checked_add_years(1)
131            .is_none_or(|limit| end_date > limit)
132        {
133            return Err(
134                ValidationError::new("end_date", "date range must not exceed one year").into(),
135            );
136        }
137        let query = [
138            ("thscode", thscode.into_string()),
139            ("start_date", start_date.to_string()),
140            ("end_date", end_date.to_string()),
141        ];
142        self.get(endpoints::HOT_STOCK_TREND, &query).await
143    }
144
145    /// 获取涨停池。
146    ///
147    /// # 示例
148    #[doc = concat!(
149        "```no_run\n",
150        include_str!("../../examples/special_data_limit_up_pool.rs"),
151        "\n```"
152    )]
153    pub async fn special_data_limit_up_pool(
154        &self,
155        date: Option<&str>,
156        page: Page,
157        sort_field: LimitUpSortField,
158        sort_dir: SortDirection,
159    ) -> Result<Response<LimitUpData>, Error> {
160        self.special_data_pool(endpoints::LIMIT_UP_POOL, date, page, sort_field, sort_dir)
161            .await
162    }
163
164    /// 获取跌停池。
165    ///
166    /// # 示例
167    #[doc = concat!(
168        "```no_run\n",
169        include_str!("../../examples/special_data_limit_down_pool.rs"),
170        "\n```"
171    )]
172    pub async fn special_data_limit_down_pool(
173        &self,
174        date: Option<&str>,
175        page: Page,
176        sort_field: LimitDownSortField,
177        sort_dir: SortDirection,
178    ) -> Result<Response<LimitDownData>, Error> {
179        self.special_data_pool(endpoints::LIMIT_DOWN_POOL, date, page, sort_field, sort_dir)
180            .await
181    }
182
183    /// 获取炸板池。
184    ///
185    /// # 示例
186    #[doc = concat!(
187        "```no_run\n",
188        include_str!("../../examples/special_data_limit_break_pool.rs"),
189        "\n```"
190    )]
191    pub async fn special_data_limit_break_pool(
192        &self,
193        date: Option<&str>,
194        page: Page,
195        sort_field: LimitBreakSortField,
196        sort_dir: SortDirection,
197    ) -> Result<Response<LimitBreakData>, Error> {
198        self.special_data_pool(
199            endpoints::LIMIT_BREAK_POOL,
200            date,
201            page,
202            sort_field,
203            sort_dir,
204        )
205        .await
206    }
207
208    async fn special_data_pool<T: DeserializeOwned>(
209        &self,
210        path: &str,
211        date: Option<&str>,
212        page: Page,
213        sort_field: impl std::fmt::Display,
214        sort_dir: SortDirection,
215    ) -> Result<Response<T>, Error> {
216        let mut query = vec![
217            ("page", page.number().to_string()),
218            ("size", page.size().to_string()),
219            ("sort_field", sort_field.to_string()),
220            ("sort_dir", sort_dir.to_string()),
221        ];
222        if let Some(date) = date {
223            let date_ms = ShanghaiDateMillis::from_date(NaturalDate::parse(date)?)?;
224            query.push(("date_ms", date_ms.to_string()));
225        }
226        self.get(path, &query).await
227    }
228
229    fn validate_recent_date(
230        &self,
231        date: NaturalDate,
232        field: &'static str,
233    ) -> Result<(), ValidationError> {
234        let today = self.shanghai_today();
235        let earliest = today
236            .checked_add_years(-1)
237            .ok_or_else(|| ValidationError::new(field, "could not calculate one-year window"))?;
238        if date < earliest || date > today {
239            return Err(ValidationError::new(
240                field,
241                "must be within the previous natural year and not in the future",
242            ));
243        }
244        Ok(())
245    }
246
247    /// 获取固定覆盖 30 个交易日的连板天梯。
248    ///
249    /// # 示例
250    #[doc = concat!(
251        "```no_run\n",
252        include_str!("../../examples/special_data_limit_up_ladder.rs"),
253        "\n```"
254    )]
255    pub async fn special_data_limit_up_ladder(&self) -> Result<Response<LadderData>, Error> {
256        self.get(endpoints::LIMIT_UP_LADDER, &[] as &[(&str, &str)])
257            .await
258    }
259
260    /// 获取当前飙升榜。
261    ///
262    /// # 示例
263    #[doc = concat!(
264        "```no_run\n",
265        include_str!("../../examples/special_data_skyrocket_list.rs"),
266        "\n```"
267    )]
268    pub async fn special_data_skyrocket_list(
269        &self,
270        period: HotListPeriod,
271    ) -> Result<Response<HotStockData>, Error> {
272        self.get(endpoints::SKYROCKET_LIST, &[("period", period.to_string())])
273            .await
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280    use crate::{AShareCode, ApiKey};
281
282    fn client() -> Client {
283        Client::builder(ApiKey::new("test-api-key").unwrap())
284            .base_url("http://127.0.0.1:9")
285            .reference_date(NaturalDate::parse("2026-08-25").unwrap())
286            .build()
287            .unwrap()
288    }
289
290    #[tokio::test]
291    async fn stock_analysis_rejects_more_than_fifty_targets_before_transport() {
292        let stock = AShareCode::new("600519.SH").unwrap();
293
294        let error = client()
295            .special_data_anomaly_analysis_stock(&vec![stock; 51])
296            .await
297            .unwrap_err();
298
299        assert!(matches!(error, Error::InvalidInput(_)));
300    }
301
302    #[tokio::test]
303    async fn recent_date_capabilities_enforce_their_documented_windows() {
304        let client = client();
305        let stock = AShareCode::new("600519.SH").unwrap();
306
307        for error in [
308            client
309                .special_data_hot_stock_rank_trend(&stock, "2024-02-29", "2025-03-01")
310                .await
311                .unwrap_err(),
312            client
313                .special_data_hot_stock_list_history("2025-08-24")
314                .await
315                .unwrap_err(),
316            client
317                .special_data_dragon_tiger_list(DragonTigerBoard::All, Some("2026-08-26"))
318                .await
319                .unwrap_err(),
320        ] {
321            assert!(matches!(error, Error::InvalidInput(_)));
322        }
323    }
324}