1use serde::{Deserialize, Deserializer};
2
3use crate::{
4 AShareCode, AuctionPhase, CompactDate, DragonTigerBoard, FinancialAbilityKind,
5 FinancialIndicatorId, FinancialPeriod, FinancialReport, FiscalPeriod, NaturalDate,
6 PreciseDecimal, RankTrend, UnixMillis, ValidationError,
7};
8
9use super::TimestampedItems;
10
11#[derive(Debug, Clone, PartialEq, Deserialize)]
13pub struct AdjustmentFactorsData {
14 pub thscode: AShareCode,
15 pub ticker: String,
16 pub item: Vec<AdjustmentFactorItem>,
17}
18
19#[derive(Debug, Clone, PartialEq, Deserialize)]
20pub struct AdjustmentFactorItem {
21 pub ticker: String,
22 pub ex_date_ms: UnixMillis,
23 pub dividend_per_share: f64,
24 pub per_share_bonus: f64,
25}
26
27#[derive(Debug, Clone, PartialEq, Deserialize)]
29pub struct FinancialStatementMeta {
30 pub thscode: AShareCode,
31 pub ticker: String,
32 pub period: FinancialPeriod,
33 pub fiscal_year: i32,
34 pub fiscal_period: FiscalPeriod,
35 pub report_date_ms: UnixMillis,
36 pub period_end_ms: UnixMillis,
37 pub currency: String,
38}
39
40#[derive(Debug, Clone, PartialEq, Deserialize)]
41pub struct IncomeStatementItem {
42 #[serde(flatten)]
43 pub meta: FinancialStatementMeta,
44 pub operating_income: Option<f64>,
45 pub operating_costs: Option<f64>,
46 pub operating_expenses: Option<f64>,
47 pub sales_fee: Option<f64>,
48 pub manage_fee: Option<f64>,
49 pub research_and_development_expenses: Option<f64>,
50 pub operating_profit: Option<f64>,
51 pub interest_expenses: Option<f64>,
52 pub profit_total: Option<f64>,
53 pub income_tax_expense: Option<f64>,
54 pub net_profit: Option<f64>,
55 pub parent_holder_net_profit: Option<f64>,
56 pub basic_eps: Option<f64>,
57}
58
59pub type IncomeStatementsData = TimestampedItems<IncomeStatementItem>;
60
61#[derive(Debug, Clone, PartialEq, Deserialize)]
62pub struct BalanceSheetItem {
63 #[serde(flatten)]
64 pub meta: FinancialStatementMeta,
65 pub assets_total: Option<f64>,
66 pub total_current_assets: Option<f64>,
67 pub non_current_nets_total: Option<f64>,
68 pub cash: Option<f64>,
69 pub accounts_receivable: Option<f64>,
70 pub total_debt: Option<f64>,
71 pub holder_equity_total: Option<f64>,
72}
73
74pub type BalanceSheetsData = TimestampedItems<BalanceSheetItem>;
75
76#[derive(Debug, Clone, PartialEq, Deserialize)]
77pub struct CashFlowStatementItem {
78 #[serde(flatten)]
79 pub meta: FinancialStatementMeta,
80 pub act_cash_flow_net: Option<f64>,
81 pub invest_cash_flow_net: Option<f64>,
82 pub financing_cash_flow_net: Option<f64>,
83 pub pay_fixed_assets_etc_cash: Option<f64>,
84 pub pay_dividends_profits_interest_cash: Option<f64>,
85 pub cash_equivalents_net_addition: Option<f64>,
86}
87
88pub type CashFlowStatementsData = TimestampedItems<CashFlowStatementItem>;
89
90#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
91pub struct FinancialIndicatorsData {
92 pub thscode: AShareCode,
93 pub report: FinancialReport,
94 pub abilities: Vec<FinancialAbility>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
98pub struct FinancialAbility {
99 pub ability: FinancialAbilityKind,
100 pub indicators: Vec<FinancialIndicator>,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
104pub struct FinancialIndicator {
105 pub index_id: FinancialIndicatorId,
106 pub value: Option<String>,
107}
108
109pub type TradingDaysData = TimestampedItems<TradingDayItem>;
110
111#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
112pub struct TradingDayItem {
113 pub date_ms: UnixMillis,
114 pub date: CompactDate,
115}
116
117#[derive(Debug, Clone, PartialEq, Deserialize)]
118pub struct AuctionSnapshotData {
119 pub timestamp: UnixMillis,
120 pub auction_phase: AuctionPhase,
121 pub data_status: String,
122 pub total: u64,
123 pub item: Vec<AuctionSnapshotItem>,
124}
125
126#[derive(Debug, Clone, PartialEq, Deserialize)]
127pub struct AuctionSnapshotItem {
128 pub thscode: AShareCode,
129 pub ticker: String,
130 pub name: String,
131 pub auction_price: Option<f64>,
132 pub auction_pct: Option<f64>,
133 pub auction_volume: Option<f64>,
134 pub auction_amount: Option<f64>,
135 pub auction_unmatched: Option<f64>,
136 pub auction_turnover_pct: Option<f64>,
137 pub auction_yesterday_ratio_pct: Option<f64>,
138 pub auction_volume_ratio: Option<f64>,
139 pub pre_close_price: Option<f64>,
140 pub open_price: Option<f64>,
141 pub last_price: Option<f64>,
142 pub float_market_cap: Option<f64>,
143}
144
145#[derive(Debug, Clone, PartialEq, Deserialize)]
146pub struct AuctionBenchmarkData {
147 pub timestamp: UnixMillis,
148 pub date: NaturalDate,
149 pub date_ms: UnixMillis,
150 pub item: Vec<AuctionBenchmarkItem>,
151}
152
153#[derive(Debug, Clone, PartialEq, Deserialize)]
154pub struct AuctionBenchmarkItem {
155 pub thscode: AShareCode,
156 pub ticker: String,
157 pub name: String,
158 pub auction_pct: Option<f64>,
159 pub tags: Vec<String>,
160}
161
162#[derive(Debug, Clone, PartialEq, Deserialize)]
163pub struct ValuationsData {
164 pub timestamp: Option<UnixMillis>,
165 pub total: u64,
166 pub item: Vec<ValuationItem>,
167}
168
169#[derive(Debug, Clone, PartialEq, Deserialize)]
170pub struct ValuationItem {
171 pub thscode: AShareCode,
172 pub ticker: String,
173 pub name: Option<String>,
174 pub pe_ttm: Option<PreciseDecimal>,
175 pub pe_mrq: Option<PreciseDecimal>,
176 pub pb_mrq: Option<PreciseDecimal>,
177 pub ps_ttm: Option<PreciseDecimal>,
178 pub pcf_ttm: Option<PreciseDecimal>,
179}
180
181pub type AnomalyData = TimestampedItems<AnomalyItem>;
182
183#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
184pub struct AnomalyItem {
185 pub stock_name: String,
186 pub analysis_content: String,
187 pub keyword_list: Vec<String>,
188 pub thscode: AShareCode,
189 pub tag_name: String,
190}
191
192pub type HotStockData = TimestampedItems<HotStockItem>;
193
194#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
195pub struct HotStockItem {
196 pub thscode: AShareCode,
197 pub ticker: String,
198 pub name: String,
199 pub rank: u64,
200 pub heat: String,
201 pub rank_change: Option<i64>,
202 pub rank_trend: RankTrend,
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
206pub struct HotStockHistoryData {
207 pub date: NaturalDate,
208 pub date_ms: UnixMillis,
209 pub item: Vec<HotStockHistoryItem>,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
213pub struct HotStockHistoryItem {
214 pub thscode: AShareCode,
215 pub ticker: String,
216 pub name: String,
217 pub rank: u64,
218}
219
220pub type HotStockTrendData = TimestampedItems<HotStockTrendItem>;
221
222#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
223pub struct HotStockTrendItem {
224 pub thscode: AShareCode,
225 pub ticker: String,
226 pub date: NaturalDate,
227 pub date_ms: UnixMillis,
228 pub rank: u64,
229}
230
231#[derive(Debug, Clone, PartialEq, Deserialize)]
232pub struct DragonTigerData {
233 pub timestamp: UnixMillis,
234 pub board_type: DragonTigerBoard,
235 pub trade_date: NaturalDate,
236 pub count: u64,
237 pub stock_count: u64,
238 pub stock_items: Vec<DragonTigerStockItem>,
239 pub hot_money_items: Vec<HotMoneyItem>,
240}
241
242#[derive(Debug, Clone, PartialEq, Deserialize)]
243pub struct ConceptItem {
244 pub name: String,
245}
246
247#[derive(Debug, Clone, PartialEq, Deserialize)]
248pub struct DragonTigerStockItem {
249 pub thscode: AShareCode,
250 pub ticker: String,
251 pub name: String,
252 #[serde(default)]
253 pub concept_list: Vec<ConceptItem>,
254 pub change: Option<f64>,
255 pub net_value: Option<f64>,
256 pub net_rate: Option<f64>,
257 pub hot_rank: Option<u64>,
258 pub buy_value: Option<f64>,
259 pub sell_value: Option<f64>,
260 pub limit_reason: Option<String>,
261 pub range_days: Option<u64>,
262 pub org_net_value: Option<f64>,
263 pub org_net_rate: Option<f64>,
264 pub org_buy_num: Option<u64>,
265 pub org_sell_num: Option<u64>,
266 pub amount: Option<f64>,
267 pub hot_money_net_value: Option<f64>,
268 pub hot_money_net_rate: Option<f64>,
269 pub hot_money_item_net_value: Option<f64>,
270 pub hot_money_item_net_rate: Option<f64>,
271}
272
273#[derive(Debug, Clone, PartialEq, Deserialize)]
274pub struct HotMoneyItem {
275 pub name: String,
276 pub buying: f64,
277 pub rows: Vec<DragonTigerStockItem>,
278}
279
280#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
281pub struct Pagination {
282 pub total: u64,
283 pub pages: u64,
284 pub size: u16,
285 pub page: u32,
286}
287
288#[derive(Debug, Clone, PartialEq, Deserialize)]
289pub struct PoolData<T> {
290 pub timestamp: UnixMillis,
291 pub pagination: Pagination,
292 pub item: Vec<T>,
293}
294
295#[derive(Debug, Clone, PartialEq, Deserialize)]
296pub struct LimitUpItem {
297 pub thscode: AShareCode,
298 pub ticker: String,
299 pub name: String,
300 pub is_st: bool,
301 pub is_new: bool,
302 pub last_price: f64,
303 pub price_change_ratio_pct: f64,
304 pub limit_up_time: String,
305 pub limit_up_reason: Option<String>,
306 pub continue_day_text: String,
307 pub continue_day_cnt: u64,
308 pub seal_money: f64,
309 pub max_seal_money: f64,
310}
311
312#[derive(Debug, Clone, PartialEq, Deserialize)]
313pub struct LimitDownItem {
314 pub thscode: AShareCode,
315 pub ticker: String,
316 pub name: String,
317 pub last_price: f64,
318 pub price_change_ratio_pct: f64,
319 pub first_limit_time: String,
320 pub last_limit_time: String,
321 pub turnover_ratio_pct: f64,
322}
323
324#[derive(Debug, Clone, PartialEq, Deserialize)]
325pub struct LimitBreakItem {
326 pub thscode: AShareCode,
327 pub ticker: String,
328 pub name: String,
329 pub last_price: f64,
330 pub price_change_ratio_pct: f64,
331 pub open_times: u64,
332 pub turnover_ratio_pct: f64,
333 pub turnover: f64,
334}
335
336pub type LimitUpData = PoolData<LimitUpItem>;
337pub type LimitDownData = PoolData<LimitDownItem>;
338pub type LimitBreakData = PoolData<LimitBreakItem>;
339
340#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
341pub struct LadderData {
342 pub timestamp: UnixMillis,
343 pub window: LadderWindow,
344 pub item: Vec<LadderDay>,
345}
346
347#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
348pub struct LadderWindow {
349 pub length: u64,
350 #[serde(deserialize_with = "deserialize_ladder_dates")]
351 pub date_list: Vec<NaturalDate>,
352 pub board_caps: LadderBoardCaps,
353}
354
355#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
356pub struct LadderBoardCaps {
357 pub two_board: u64,
358 pub three_board: u64,
359 pub four_board: u64,
360 pub five_board: u64,
361 pub six_board: u64,
362 pub seven_over: u64,
363}
364
365#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
366pub struct LadderDay {
367 #[serde(deserialize_with = "deserialize_ladder_date")]
368 pub date: NaturalDate,
369 pub boards: LadderBoards,
370}
371
372#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
373pub struct LadderBoards {
374 pub two_board: Vec<LadderStock>,
375 pub three_board: Vec<LadderStock>,
376 pub four_board: Vec<LadderStock>,
377 pub five_board: Vec<LadderStock>,
378 pub six_board: Vec<LadderStock>,
379 pub seven_over: Vec<LadderStock>,
380}
381
382#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
383pub struct LadderStock {
384 pub thscode: AShareCode,
385 pub ticker: String,
386 pub name: String,
387 pub board_num: u64,
388 pub seal_nextday: Option<bool>,
389 pub sign_level: u64,
390}
391
392fn deserialize_ladder_dates<'de, D>(deserializer: D) -> Result<Vec<NaturalDate>, D::Error>
393where
394 D: Deserializer<'de>,
395{
396 Vec::<String>::deserialize(deserializer)?
397 .into_iter()
398 .map(|value| parse_ladder_date(&value).map_err(serde::de::Error::custom))
399 .collect()
400}
401
402fn deserialize_ladder_date<'de, D>(deserializer: D) -> Result<NaturalDate, D::Error>
403where
404 D: Deserializer<'de>,
405{
406 let value = String::deserialize(deserializer)?;
407 parse_ladder_date(&value).map_err(serde::de::Error::custom)
408}
409
410fn parse_ladder_date(value: &str) -> Result<NaturalDate, ValidationError> {
411 match value.len() {
412 8 => CompactDate::parse(value).map(CompactDate::natural_date),
413 10 => NaturalDate::parse(value),
414 _ => Err(ValidationError::new(
415 "date",
416 "must use YYYYMMDD or YYYY-MM-DD format",
417 )),
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use serde_json::json;
424
425 use crate::{
426 AuctionSnapshotData, FinancialIndicatorsData, HotStockData, IncomeStatementsData,
427 LadderData, TradingDaysData, ValuationsData,
428 };
429
430 #[test]
431 fn auction_snapshot_accepts_the_observed_closed_response_phase() {
432 let snapshot: AuctionSnapshotData = serde_json::from_value(json!({
433 "timestamp": 1_i64,
434 "auction_phase": "closed",
435 "data_status": "final",
436 "total": 0,
437 "item": []
438 }))
439 .unwrap();
440
441 assert_eq!(snapshot.auction_phase.as_str(), "closed");
442 }
443
444 #[test]
445 fn financial_indicators_accept_observed_upstream_identifiers() {
446 let indicators: FinancialIndicatorsData = serde_json::from_value(json!({
447 "thscode": "600519.SH",
448 "report": "2025-4",
449 "abilities": [{
450 "ability": "growth",
451 "indicators": [
452 {
453 "index_id": "calculate_operating_income_yoy_growth_ratio",
454 "value": "-1.20600400"
455 },
456 {
457 "index_id": "calculate_operating_profit_yoy_growth_ratio",
458 "value": "-4.07693800"
459 },
460 {
461 "index_id": "fixed_asset_invest_expansion_ratio",
462 "value": "2.81954600"
463 },
464 {
465 "index_id": "calculate_parent_holder_net_profit_yoy_growth_ratio",
466 "value": "-4.53225500"
467 }
468 ]
469 }]
470 }))
471 .unwrap();
472
473 let identifiers = indicators.abilities[0]
474 .indicators
475 .iter()
476 .map(|indicator| indicator.index_id.as_str())
477 .collect::<Vec<_>>();
478 assert_eq!(
479 identifiers,
480 [
481 "operating_income_yoy_growth_ratio",
482 "operating_profit_yoy_growth_ratio",
483 "fixed_asset_invest_expansion_ratio",
484 "parent_holder_net_profit_yoy_growth_ratio",
485 ]
486 );
487 }
488
489 #[test]
490 fn finite_response_states_reject_unknown_wire_values() {
491 let hot_stock = json!({
492 "timestamp": 1_i64,
493 "item": [{
494 "thscode": "600519.SH",
495 "ticker": "600519",
496 "name": "贵州茅台",
497 "rank": 1,
498 "heat": "100",
499 "rank_trend": "sideways"
500 }]
501 });
502 assert!(serde_json::from_value::<HotStockData>(hot_stock).is_err());
503
504 let statement = json!({
505 "timestamp": 1_i64,
506 "item": [{
507 "thscode": "600519.SH",
508 "ticker": "600519",
509 "period": "annual",
510 "fiscal_year": 2025,
511 "fiscal_period": "H1",
512 "report_date_ms": 1_i64,
513 "period_end_ms": 1_i64,
514 "currency": "CNY"
515 }]
516 });
517 assert!(serde_json::from_value::<IncomeStatementsData>(statement).is_err());
518
519 for indicators in [
520 json!({
521 "thscode": "600519.SH",
522 "report": "2025-4",
523 "abilities": [{"ability": "momentum", "indicators": []}]
524 }),
525 json!({
526 "thscode": "600519.SH",
527 "report": "2025-4",
528 "abilities": [{
529 "ability": "growth",
530 "indicators": [{"index_id": "unknown_ratio", "value": null}]
531 }]
532 }),
533 ] {
534 assert!(serde_json::from_value::<FinancialIndicatorsData>(indicators).is_err());
535 }
536 }
537
538 #[test]
539 fn compact_wire_dates_are_validated_at_deserialization() {
540 let trading_days = json!({
541 "timestamp": 1_i64,
542 "item": [{"date_ms": 1_i64, "date": "20250229"}]
543 });
544 assert!(serde_json::from_value::<TradingDaysData>(trading_days).is_err());
545
546 let ladder = json!({
547 "timestamp": 1_i64,
548 "window": {
549 "length": 1,
550 "date_list": ["20250229"],
551 "board_caps": {
552 "two_board": 0,
553 "three_board": 0,
554 "four_board": 0,
555 "five_board": 0,
556 "six_board": 0,
557 "seven_over": 0
558 }
559 },
560 "item": []
561 });
562 assert!(serde_json::from_value::<LadderData>(ladder).is_err());
563 }
564
565 #[test]
566 fn ladder_accepts_observed_hyphenated_natural_dates() {
567 let ladder: LadderData = serde_json::from_value(json!({
568 "timestamp": 1_i64,
569 "window": {
570 "length": 2,
571 "date_list": ["2026-08-26", "20260825"],
572 "board_caps": {
573 "two_board": 4,
574 "three_board": 4,
575 "four_board": 4,
576 "five_board": 2,
577 "six_board": 1,
578 "seven_over": 1
579 }
580 },
581 "item": [
582 {
583 "date": "2026-08-26",
584 "boards": {
585 "two_board": [],
586 "three_board": [],
587 "four_board": [],
588 "five_board": [],
589 "six_board": [],
590 "seven_over": []
591 }
592 },
593 {
594 "date": "20260825",
595 "boards": {
596 "two_board": [],
597 "three_board": [],
598 "four_board": [],
599 "five_board": [],
600 "six_board": [],
601 "seven_over": []
602 }
603 }
604 ]
605 }))
606 .unwrap();
607
608 assert_eq!(ladder.window.date_list[0].to_string(), "2026-08-26");
609 assert_eq!(ladder.window.date_list[1].to_string(), "2026-08-25");
610 assert_eq!(ladder.item[0].date.to_string(), "2026-08-26");
611 assert_eq!(ladder.item[1].date.to_string(), "2026-08-25");
612 }
613
614 #[test]
615 fn documented_nullable_valuation_metadata_is_preserved() {
616 let valuations: ValuationsData = serde_json::from_value(json!({
617 "timestamp": null,
618 "total": 1,
619 "item": [{
620 "thscode": "600519.SH",
621 "ticker": "600519",
622 "name": null,
623 "pe_ttm": null,
624 "pe_mrq": null,
625 "pb_mrq": null,
626 "ps_ttm": null,
627 "pcf_ttm": null
628 }]
629 }))
630 .unwrap();
631
632 assert_eq!(valuations.timestamp, None);
633 assert_eq!(valuations.item[0].name, None);
634 }
635
636 #[test]
637 fn valuation_decimals_preserve_digits_beyond_binary_float_precision() {
638 let data: ValuationsData = serde_json::from_str(
639 r#"{
640 "timestamp": 1,
641 "total": 1,
642 "item": [{
643 "thscode": "600519.SH",
644 "ticker": "600519",
645 "name": "贵州茅台",
646 "pe_ttm": 123456789012345.123456,
647 "pe_mrq": -0.000000000000000000123456,
648 "pb_mrq": null,
649 "ps_ttm": null,
650 "pcf_ttm": null
651 }]
652 }"#,
653 )
654 .unwrap();
655
656 assert_eq!(
657 data.item[0].pe_ttm.as_ref().unwrap().to_string(),
658 "123456789012345.123456"
659 );
660 assert_eq!(
661 data.item[0].pe_mrq.as_ref().unwrap().to_string(),
662 "-0.000000000000000000123456"
663 );
664 }
665}