Skip to main content

longport/fundamental/
types.rs

1use std::collections::HashMap;
2
3use num_enum::{FromPrimitive, IntoPrimitive};
4use rust_decimal::Decimal;
5use serde::{Deserialize, Serialize};
6use strum_macros::{Display, EnumString};
7use time::OffsetDateTime;
8
9// ── financial_report ─────────────────────────────────────────────
10
11/// Response for [`crate::FundamentalContext::financial_report`]
12///
13/// The `list` field contains deeply-nested indicator/account/value data keyed
14/// by report kind (`"IS"`, `"BS"`, `"CF"`).  The exact structure varies and is
15/// preserved as raw JSON.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct FinancialReports {
18    /// Raw nested financial data. Top-level keys are report kinds such as
19    /// `"IS"` (income statement), `"BS"` (balance sheet), `"CF"` (cash flow).
20    pub list: serde_json::Value,
21}
22
23// ── dividend ─────────────────────────────────────────────────────
24
25/// Response for [`crate::FundamentalContext::dividend`] and
26/// [`crate::FundamentalContext::dividend_detail`]
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct DividendList {
29    /// List of dividend events
30    pub list: Vec<DividendItem>,
31}
32
33/// A single dividend / distribution event
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct DividendItem {
36    /// Security symbol, e.g. `"700.HK"`
37    pub symbol: String,
38    /// Internal record ID (may be absent in dividend_detail response)
39    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
40    pub id: String,
41    /// Human-readable description, e.g. `"每股派息 5.3 HKD"`
42    pub desc: String,
43    /// Record / book-close date, e.g. `"2026.05.18"`
44    pub record_date: String,
45    /// Ex-dividend date, e.g. `"2026.05.15"`
46    pub ex_date: String,
47    /// Payment date, e.g. `"2026.06.01"`
48    pub payment_date: String,
49}
50
51// ── institution_rating ────────────────────────────────────────────
52
53/// Combined analyst-rating response for
54/// [`crate::FundamentalContext::institution_rating`]
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct InstitutionRating {
57    /// Latest snapshot from `/v1/quote/institution-rating-latest`
58    pub latest: InstitutionRatingLatest,
59    /// Consensus summary from `/v1/quote/institution-ratings`
60    pub summary: InstitutionRatingSummary,
61}
62
63/// Latest analyst-rating snapshot
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct InstitutionRatingLatest {
66    /// Rating distribution counts and date range
67    pub evaluate: RatingEvaluate,
68    /// Target price range
69    pub target: RatingTarget,
70    /// Industry classification ID
71    pub industry_id: i64,
72    /// Industry name
73    pub industry_name: String,
74    /// Rank of this security within the industry (1 = highest)
75    pub industry_rank: i32,
76    /// Total number of securities in the industry
77    pub industry_total: i32,
78    /// Mean analyst count in the industry
79    pub industry_mean: i32,
80    /// Median analyst count in the industry
81    pub industry_median: i32,
82}
83
84/// Analyst rating distribution counts
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct RatingEvaluate {
87    /// Number of "Buy" ratings
88    pub buy: i32,
89    /// Number of "Strong Buy" / "Outperform" ratings
90    pub over: i32,
91    /// Number of "Hold" / "Neutral" ratings
92    pub hold: i32,
93    /// Number of "Underperform" ratings
94    pub under: i32,
95    /// Number of "Sell" ratings
96    pub sell: i32,
97    /// Number of "No Opinion" ratings
98    pub no_opinion: i32,
99    /// Total analyst count
100    pub total: i32,
101    /// Window start (unix timestamp string; `"0"` means unset)
102    pub start_date: String,
103    /// Window end (unix timestamp string; `"0"` means unset)
104    pub end_date: String,
105}
106
107/// Analyst target price range
108#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct RatingTarget {
110    /// Highest price target
111    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
112    pub highest_price: Option<Decimal>,
113    /// Lowest price target
114    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
115    pub lowest_price: Option<Decimal>,
116    /// Previous close price
117    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
118    pub prev_close: Option<Decimal>,
119    /// Window start (unix timestamp string)
120    pub start_date: String,
121    /// Window end (unix timestamp string)
122    pub end_date: String,
123}
124
125/// Consensus summary from `/v1/quote/institution-ratings`
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct InstitutionRatingSummary {
128    /// Currency symbol, e.g. `"HK$"`
129    pub ccy_symbol: String,
130    /// Change vs previous period
131    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
132    pub change: Option<Decimal>,
133    /// Simplified rating distribution
134    pub evaluate: RatingSummaryEvaluate,
135    /// Overall recommendation
136    pub recommend: InstitutionRecommend,
137    /// Consensus target price
138    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
139    pub target: Option<Decimal>,
140    /// Last updated display string, e.g. `"2026 年 5 月 5 日"`
141    pub updated_at: String,
142}
143
144/// Simplified rating distribution for the consensus summary
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct RatingSummaryEvaluate {
147    /// Number of "Buy" ratings
148    pub buy: i32,
149    /// Date of the latest update
150    pub date: String,
151    /// Number of "Hold" ratings
152    pub hold: i32,
153    /// Number of "Sell" ratings
154    pub sell: i32,
155    /// Number of "Strong Buy" ratings
156    pub strong_buy: i32,
157    /// Number of "Underperform" ratings
158    pub under: i32,
159}
160
161// ── institution_rating_detail ─────────────────────────────────────
162
163/// Response for [`crate::FundamentalContext::institution_rating_detail`]
164#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct InstitutionRatingDetail {
166    /// Currency symbol, e.g. `"HK$"`
167    pub ccy_symbol: String,
168    /// Historical rating distribution time-series
169    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
170    pub evaluate: InstitutionRatingDetailEvaluate,
171    /// Historical target price time-series
172    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
173    pub target: InstitutionRatingDetailTarget,
174}
175
176/// Historical rating distribution time-series
177#[derive(Debug, Clone, Serialize, Deserialize, Default)]
178pub struct InstitutionRatingDetailEvaluate {
179    /// Weekly snapshots ordered from oldest to newest
180    pub list: Vec<InstitutionRatingDetailEvaluateItem>,
181}
182
183/// One weekly rating distribution snapshot
184#[derive(Debug, Clone, Serialize, Deserialize)]
185pub struct InstitutionRatingDetailEvaluateItem {
186    /// Number of "Buy" ratings
187    pub buy: i32,
188    /// Date in `"2021/05/14"` format
189    pub date: String,
190    /// Number of "Hold" ratings
191    pub hold: i32,
192    /// Number of "Sell" ratings
193    pub sell: i32,
194    /// Number of "Strong Buy" / "Outperform" ratings
195    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
196    pub strong_buy: i32,
197    /// Number of "No Opinion" ratings
198    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
199    pub no_opinion: i32,
200    /// Number of "Underperform" ratings
201    pub under: i32,
202}
203
204/// Historical target price time-series
205#[derive(Debug, Clone, Serialize, Deserialize, Default)]
206pub struct InstitutionRatingDetailTarget {
207    /// Prediction accuracy ratio, e.g. `"0.9934"` (may be `null`)
208    pub data_percent: Option<Decimal>,
209    /// Overall prediction accuracy percentage string
210    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
211    pub prediction_accuracy: Option<Decimal>,
212    /// Last updated display string
213    pub updated_at: String,
214    /// Weekly target price snapshots
215    pub list: Vec<InstitutionRatingDetailTargetItem>,
216}
217
218/// One weekly target price snapshot
219#[derive(Debug, Clone, Serialize, Deserialize)]
220pub struct InstitutionRatingDetailTargetItem {
221    /// Average target price
222    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
223    pub avg_target: Option<Decimal>,
224    /// Date in `"2021/05/16"` format
225    pub date: String,
226    /// Highest target price
227    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
228    pub max_target: Option<Decimal>,
229    /// Lowest target price
230    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
231    pub min_target: Option<Decimal>,
232    /// Whether the stock price reached the target
233    pub meet: bool,
234    /// Actual stock price at this date
235    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
236    pub price: Option<Decimal>,
237    /// Unix timestamp string
238    pub timestamp: String,
239}
240
241// ── forecast_eps ──────────────────────────────────────────────────
242
243/// Response for [`crate::FundamentalContext::forecast_eps`]
244#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct ForecastEps {
246    /// EPS forecast snapshots ordered by `forecast_start_date` ascending
247    pub items: Vec<ForecastEpsItem>,
248}
249
250/// One EPS forecast snapshot
251#[derive(Debug, Clone, Serialize, Deserialize)]
252pub struct ForecastEpsItem {
253    /// Median EPS estimate
254    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
255    pub forecast_eps_median: Option<Decimal>,
256    /// Mean EPS estimate
257    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
258    pub forecast_eps_mean: Option<Decimal>,
259    /// Lowest EPS estimate
260    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
261    pub forecast_eps_lowest: Option<Decimal>,
262    /// Highest EPS estimate
263    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
264    pub forecast_eps_highest: Option<Decimal>,
265    /// Total number of forecasting institutions
266    pub institution_total: i32,
267    /// Number of institutions that raised their estimate
268    pub institution_up: i32,
269    /// Number of institutions that lowered their estimate
270    pub institution_down: i32,
271    /// Forecast window start
272    #[serde(deserialize_with = "crate::serde_utils::deserialize_timestamp")]
273    pub forecast_start_date: OffsetDateTime,
274    /// Forecast window end
275    #[serde(deserialize_with = "crate::serde_utils::deserialize_timestamp")]
276    pub forecast_end_date: OffsetDateTime,
277}
278
279// ── consensus ─────────────────────────────────────────────────────
280
281/// Response for [`crate::FundamentalContext::consensus`]
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct FinancialConsensus {
284    /// Per-period consensus reports
285    pub list: Vec<ConsensusReport>,
286    /// Index into `list` of the most recently released period
287    pub current_index: i32,
288    /// Reporting currency, e.g. `"HKD"`
289    pub currency: String,
290    /// Available period types, e.g. `["qf", "saf", "af"]`
291    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
292    pub opt_periods: Vec<String>,
293    /// Currently returned period type
294    pub current_period: String,
295}
296
297/// Consensus report for one fiscal period
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct ConsensusReport {
300    /// Fiscal year, e.g. `2025`
301    pub fiscal_year: i32,
302    /// Fiscal period code, e.g. `"Q4"`
303    pub fiscal_period: String,
304    /// Human-readable period label, e.g. `"Q4 FY2025"`
305    pub period_text: String,
306    /// Per-metric consensus details
307    pub details: Vec<ConsensusDetail>,
308}
309
310/// Consensus estimate for one financial metric
311#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct ConsensusDetail {
313    /// Metric key, e.g. `"revenue"`, `"eps"`
314    pub key: String,
315    /// Display name
316    pub name: String,
317    /// Metric description
318    pub description: String,
319    /// Actual reported value (empty string if not yet released)
320    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
321    pub actual: Option<Decimal>,
322    /// Consensus estimate value
323    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
324    pub estimate: Option<Decimal>,
325    /// Actual minus estimate
326    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
327    pub comp_value: Option<Decimal>,
328    /// Beat/miss description, e.g. `"超出预期"`
329    pub comp_desc: String,
330    /// Comparison result code for colour coding
331    pub comp: String,
332    /// Whether the actual results have been published
333    pub is_released: bool,
334}
335
336// ── valuation ─────────────────────────────────────────────────────
337
338/// Response for [`crate::FundamentalContext::valuation`]
339#[derive(Debug, Clone, Serialize, Deserialize)]
340pub struct ValuationData {
341    /// Valuation metrics (PE / PB / PS / dividend yield)
342    pub metrics: ValuationMetricsData,
343}
344
345/// Container for all valuation metrics
346#[derive(Debug, Clone, Serialize, Deserialize)]
347pub struct ValuationMetricsData {
348    /// Price-to-Earnings ratio history
349    pub pe: Option<ValuationMetricData>,
350    /// Price-to-Book ratio history
351    pub pb: Option<ValuationMetricData>,
352    /// Price-to-Sales ratio history
353    pub ps: Option<ValuationMetricData>,
354    /// Dividend yield history
355    pub dvd_yld: Option<ValuationMetricData>,
356}
357
358/// Historical time-series for one valuation metric
359#[derive(Debug, Clone, Serialize, Deserialize)]
360pub struct ValuationMetricData {
361    /// Human-readable description with current value and percentile
362    pub desc: String,
363    /// Upper bound of the fair-value band (not the period maximum; the series
364    /// can rise above it)
365    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
366    pub high: Option<Decimal>,
367    /// Lower bound of the fair-value band (not the period minimum; the series
368    /// can fall below it)
369    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
370    pub low: Option<Decimal>,
371    /// Historical median value
372    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
373    pub median: Option<Decimal>,
374    /// Historical data points
375    pub list: Vec<ValuationPoint>,
376}
377
378/// One valuation data point
379#[derive(Debug, Clone, Serialize, Deserialize)]
380pub struct ValuationPoint {
381    /// Date of the data point
382    #[serde(deserialize_with = "crate::serde_utils::deserialize_timestamp")]
383    pub timestamp: OffsetDateTime,
384    /// Metric value
385    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
386    pub value: Option<Decimal>,
387}
388
389// ── valuation_history ─────────────────────────────────────────────
390
391/// Response for [`crate::FundamentalContext::valuation_history`]
392#[derive(Debug, Clone, Serialize, Deserialize)]
393pub struct ValuationHistoryResponse {
394    /// Historical valuation data
395    pub history: ValuationHistoryData,
396}
397
398/// Container for historical valuation metrics
399#[derive(Debug, Clone, Serialize, Deserialize)]
400pub struct ValuationHistoryData {
401    /// Historical metrics (PE / PB / PS)
402    pub metrics: ValuationHistoryMetrics,
403}
404
405/// Historical valuation metrics container
406#[derive(Debug, Clone, Serialize, Deserialize)]
407pub struct ValuationHistoryMetrics {
408    /// Price-to-Earnings history
409    pub pe: Option<ValuationHistoryMetric>,
410    /// Price-to-Book history
411    pub pb: Option<ValuationHistoryMetric>,
412    /// Price-to-Sales history
413    pub ps: Option<ValuationHistoryMetric>,
414}
415
416/// Historical data for one valuation metric including statistical bounds
417#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct ValuationHistoryMetric {
419    /// Human-readable description
420    pub desc: String,
421    /// Upper bound of the fair-value band (not the period maximum; the series
422    /// can rise above it)
423    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
424    pub high: Option<Decimal>,
425    /// Lower bound of the fair-value band (not the period minimum; the series
426    /// can fall below it)
427    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
428    pub low: Option<Decimal>,
429    /// Historical median over the period
430    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
431    pub median: Option<Decimal>,
432    /// Historical data points
433    pub list: Vec<ValuationPoint>,
434}
435
436// ── industry_valuation ────────────────────────────────────────────
437
438/// Response for [`crate::FundamentalContext::industry_valuation`]
439#[derive(Debug, Clone, Serialize, Deserialize)]
440pub struct IndustryValuationList {
441    /// List of peer securities with their valuation data
442    pub list: Vec<IndustryValuationItem>,
443}
444
445/// Valuation data for one peer security
446#[derive(Debug, Clone, Serialize, Deserialize)]
447pub struct IndustryValuationItem {
448    /// Security symbol, e.g. `"700.HK"`
449    pub symbol: String,
450    /// Company name
451    pub name: String,
452    /// Reporting currency
453    pub currency: String,
454    /// Total assets
455    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
456    pub assets: Option<Decimal>,
457    /// Book value per share
458    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
459    pub bps: Option<Decimal>,
460    /// Earnings per share
461    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
462    pub eps: Option<Decimal>,
463    /// Dividends per share
464    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
465    pub dps: Option<Decimal>,
466    /// Dividend yield
467    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
468    pub div_yld: Option<Decimal>,
469    /// Dividend payout ratio
470    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
471    pub div_payout_ratio: Option<Decimal>,
472    /// 5-year average dividends per share
473    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
474    pub five_y_avg_dps: Option<Decimal>,
475    /// Current PE ratio
476    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
477    pub pe: Option<Decimal>,
478    /// Historical PE/PB/PS snapshots
479    pub history: Vec<IndustryValuationHistory>,
480}
481
482/// Historical valuation snapshot for an industry peer
483#[derive(Debug, Clone, Serialize, Deserialize)]
484pub struct IndustryValuationHistory {
485    /// Unix timestamp string
486    pub date: String,
487    /// Price-to-Earnings ratio
488    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
489    pub pe: Option<Decimal>,
490    /// Price-to-Book ratio
491    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
492    pub pb: Option<Decimal>,
493    /// Price-to-Sales ratio
494    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
495    pub ps: Option<Decimal>,
496}
497
498// ── industry_valuation_dist ───────────────────────────────────────
499
500/// Response for [`crate::FundamentalContext::industry_valuation_dist`]
501#[derive(Debug, Clone, Serialize, Deserialize)]
502pub struct IndustryValuationDist {
503    /// PE ratio distribution within the industry
504    pub pe: Option<ValuationDist>,
505    /// PB ratio distribution within the industry
506    pub pb: Option<ValuationDist>,
507    /// PS ratio distribution within the industry
508    pub ps: Option<ValuationDist>,
509}
510
511/// Distribution statistics for one valuation metric within an industry
512#[derive(Debug, Clone, Serialize, Deserialize)]
513pub struct ValuationDist {
514    /// Minimum value in the industry
515    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
516    pub low: Option<Decimal>,
517    /// Maximum value in the industry
518    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
519    pub high: Option<Decimal>,
520    /// Median value in the industry
521    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
522    pub median: Option<Decimal>,
523    /// Current value of the queried security
524    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
525    pub value: Option<Decimal>,
526    /// Percentile ranking (0–1 range as string)
527    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
528    pub ranking: Option<Decimal>,
529    /// Ordinal rank index (1-based)
530    pub rank_index: String,
531    /// Total number of securities in the industry
532    pub rank_total: String,
533}
534
535// ── company ───────────────────────────────────────────────────────
536
537/// Response for [`crate::FundamentalContext::company`]
538#[derive(Debug, Clone, Serialize, Deserialize)]
539pub struct CompanyOverview {
540    /// Short name, e.g. `"腾讯控股"`
541    pub name: String,
542    /// Full legal name
543    pub company_name: String,
544    /// Founding date
545    pub founded: String,
546    /// Listing date
547    pub listing_date: String,
548    /// Primary listing market display name
549    pub market: String,
550    /// Market region code, e.g. `"HK"`
551    pub region: String,
552    /// Registered address
553    pub address: String,
554    /// Principal office address
555    pub office_address: String,
556    /// Company website
557    pub website: String,
558    /// IPO issue price
559    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
560    pub issue_price: Option<Decimal>,
561    /// Number of shares offered at IPO
562    pub shares_offered: String,
563    /// Chairman name
564    pub chairman: String,
565    /// Company secretary name
566    pub secretary: String,
567    /// Auditing institution
568    pub audit_inst: String,
569    /// Company classification category
570    pub category: String,
571    /// Fiscal year end, e.g. `"12 月 31 日"`
572    pub year_end: String,
573    /// Number of employees (returned as a string by the API, e.g. `"10000"`)
574    pub employees: String,
575    /// Phone number (API field name is `"Phone"`)
576    #[serde(rename = "Phone")]
577    pub phone: String,
578    /// Fax number
579    pub fax: String,
580    /// Investor relations email
581    pub email: String,
582    /// Legal representative
583    pub legal_repr: String,
584    /// CEO / Managing Director
585    pub manager: String,
586    /// Business licence number
587    pub bus_license: String,
588    /// Accounting firm
589    pub accounting_firm: String,
590    /// Securities representative
591    pub securities_rep: String,
592    /// Legal counsel
593    pub legal_counsel: String,
594    /// Postal code
595    pub zip_code: String,
596    /// Exchange ticker code, e.g. `"00700"`
597    pub ticker: String,
598    /// URL to the company's logo icon
599    pub icon: String,
600    /// Business profile / description
601    pub profile: String,
602    /// ADS ratio (may be empty)
603    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
604    pub ads_ratio: String,
605    /// Industry sector code
606    pub sector: i32,
607}
608
609// ── executive ─────────────────────────────────────────────────────
610
611/// Response for [`crate::FundamentalContext::executive`]
612#[derive(Debug, Clone, Serialize, Deserialize)]
613pub struct ExecutiveList {
614    /// Groups of executives per security (usually one group)
615    pub professional_list: Vec<ExecutiveGroup>,
616}
617
618/// Executives for one security
619#[derive(Debug, Clone, Serialize, Deserialize)]
620pub struct ExecutiveGroup {
621    /// Security symbol (`None` when the server omits it or returns empty)
622    #[serde(default, with = "crate::serde_utils::symbol_opt")]
623    pub symbol: Option<String>,
624    /// Link to the company wiki page
625    pub forward_url: String,
626    /// Total number of executives
627    pub total: i32,
628    /// Individual executive entries
629    pub professionals: Vec<Professional>,
630}
631
632/// One executive / board member
633#[derive(Debug, Clone, Serialize, Deserialize)]
634pub struct Professional {
635    /// Internal wiki person ID (string form)
636    pub id: String,
637    /// Full name
638    pub name: String,
639    /// Full name in Simplified Chinese
640    pub name_zhcn: String,
641    /// Full name in English
642    pub name_en: String,
643    /// Job title, e.g. `"Co-Founder, Chairman & CEO"`
644    pub title: String,
645    /// Biography text
646    pub biography: String,
647    /// URL to the person's photo
648    pub photo: String,
649    /// URL to the wiki profile page
650    pub wiki_url: String,
651}
652
653// ── shareholder ───────────────────────────────────────────────────
654
655/// Response for [`crate::FundamentalContext::shareholder`]
656#[derive(Debug, Clone, Serialize, Deserialize)]
657pub struct ShareholderList {
658    /// List of major shareholders
659    pub shareholder_list: Vec<Shareholder>,
660    /// Link to the full shareholder page
661    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
662    pub forward_url: String,
663    /// Total number of shareholders returned
664    pub total: i32,
665}
666
667/// One major shareholder
668#[derive(Debug, Clone, Serialize, Deserialize)]
669pub struct Shareholder {
670    /// Internal shareholder ID (string form)
671    pub shareholder_id: String,
672    /// Shareholder name
673    pub shareholder_name: String,
674    /// Institution type (may be empty)
675    pub institution_type: String,
676    /// Percentage of shares held
677    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
678    pub percent_of_shares: Option<Decimal>,
679    /// Change in shares held (positive = bought, negative = sold)
680    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
681    pub shares_changed: Option<Decimal>,
682    /// Date of the most recent filing, e.g. `"2026-05-04"`
683    pub report_date: String,
684    /// Other securities held by this shareholder (cross-holdings)
685    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
686    pub stocks: Vec<ShareholderStock>,
687}
688
689/// A security in an institutional shareholder's cross-holdings
690#[derive(Debug, Clone, Serialize, Deserialize)]
691pub struct ShareholderStock {
692    /// Security symbol of the cross-held stock
693    pub symbol: String,
694    /// Ticker code, e.g. `"BLK"`
695    pub code: String,
696    /// Market, e.g. `"US"`
697    pub market: String,
698    /// Day change percentage, e.g. `"-0.32%"`
699    pub chg: String,
700}
701
702// ── fund_holder ───────────────────────────────────────────────────
703
704/// Response for [`crate::FundamentalContext::fund_holder`]
705#[derive(Debug, Clone, Serialize, Deserialize)]
706pub struct FundHolders {
707    /// Funds and ETFs that hold the queried security
708    pub lists: Vec<FundHolder>,
709}
710
711/// A fund or ETF that holds the queried security
712#[derive(Debug, Clone, Serialize, Deserialize)]
713pub struct FundHolder {
714    /// Fund/ETF ticker code, e.g. `"513050"`
715    pub code: String,
716    /// Fund/ETF symbol, e.g. `"513050.SH"`
717    pub symbol: String,
718    /// Reporting currency, e.g. `"CNY"`
719    pub currency: String,
720    /// Fund/ETF full name
721    pub name: String,
722    /// Position ratio as a percentage decimal
723    #[serde(with = "crate::serde_utils::decimal_empty_is_0")]
724    pub position_ratio: Decimal,
725    /// Report date, e.g. `"2025.12.31"`
726    pub report_date: String,
727}
728
729// ── corp_action ───────────────────────────────────────────────────
730
731/// Response for [`crate::FundamentalContext::corp_action`]
732#[derive(Debug, Clone, Serialize, Deserialize)]
733pub struct CorpActions {
734    /// Corporate action events
735    pub items: Vec<CorpActionItem>,
736}
737
738/// One corporate action event
739#[derive(Debug, Clone, Serialize, Deserialize)]
740pub struct CorpActionItem {
741    /// Internal event ID
742    pub id: String,
743    /// Date in `YYYYMMDD` format, e.g. `"20260601"`
744    pub date: String,
745    /// Short display date, e.g. `"06.01"`
746    pub date_str: String,
747    /// Date type label, e.g. `"派息日"`, `"除权日"`
748    pub date_type: String,
749    /// Time zone description, e.g. `"北京时间"`
750    pub date_zone: String,
751    /// Event category, e.g. `"分配方案"`
752    pub act_type: String,
753    /// Human-readable event description
754    pub act_desc: String,
755    /// Machine-readable action code, e.g. `"DividendExDate"`
756    pub action: String,
757    /// Whether this is a recent event
758    pub recent: bool,
759    /// Whether publication was delayed
760    pub is_delay: bool,
761    /// Delay announcement content (if `is_delay` is `true`)
762    pub delay_content: String,
763    /// Associated live stream (if any)
764    pub live: Option<CorpActionLive>,
765    /// Associated security info (rarely populated; preserved as raw JSON)
766    pub security: Option<serde_json::Value>,
767}
768
769/// Live stream associated with a corporate action
770#[derive(Debug, Clone, Serialize, Deserialize)]
771pub struct CorpActionLive {
772    /// Live stream ID
773    pub id: String,
774    /// Status code: 1=preview, 2=live, 3=ended, 4=replay, 5=processing.
775    ///
776    /// The API may return this as either an integer or a string; it is
777    /// normalized to a string.
778    #[serde(deserialize_with = "crate::serde_utils::deserialize_string_or_int_as_string")]
779    pub status: String,
780    /// Start time
781    pub started_at: String,
782    /// Stream title
783    pub name: String,
784    /// Icon URL
785    pub icon: String,
786}
787
788// ── invest_relation ───────────────────────────────────────────────
789
790/// Response for [`crate::FundamentalContext::invest_relation`]
791#[derive(Debug, Clone, Serialize, Deserialize)]
792pub struct InvestRelations {
793    /// Link to the full investor-relations page
794    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
795    pub forward_url: String,
796    /// Securities in which the queried company holds a stake
797    pub invest_securities: Vec<InvestSecurity>,
798}
799
800/// A security in which the queried company has an investment stake
801#[derive(Debug, Clone, Serialize, Deserialize)]
802pub struct InvestSecurity {
803    /// Internal company ID (string form; may be `"0"`)
804    pub company_id: String,
805    /// Company name (locale-aware)
806    pub company_name: String,
807    /// Company name in English
808    pub company_name_en: String,
809    /// Company name in Simplified Chinese
810    pub company_name_zhcn: String,
811    /// Security symbol of the invested company
812    pub symbol: String,
813    /// Reporting currency
814    pub currency: String,
815    /// Percentage of shares held
816    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
817    pub percent_of_shares: Option<Decimal>,
818    /// Shareholder rank, e.g. `"1"` = largest shareholder
819    pub shares_rank: String,
820    /// Market value of the holding
821    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
822    pub shares_value: Option<Decimal>,
823}
824
825// ── operating ─────────────────────────────────────────────────────
826
827/// Response for [`crate::FundamentalContext::operating`]
828#[derive(Debug, Clone, Serialize, Deserialize)]
829pub struct OperatingList {
830    /// List of operating summary reports
831    pub list: Vec<OperatingItem>,
832}
833
834/// One operating summary report (annual / quarterly)
835#[derive(Debug, Clone, Serialize, Deserialize)]
836pub struct OperatingItem {
837    /// Internal report ID
838    pub id: String,
839    /// Report period code, e.g. `"af"` (annual), `"qf"` (quarterly)
840    pub report: String,
841    /// Report title, e.g. `"2025 财年年报"`
842    pub title: String,
843    /// Management discussion text
844    pub txt: String,
845    /// Whether this is the most recent report
846    pub latest: bool,
847    /// Keyword tags (structure undocumented; usually empty)
848    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
849    pub keywords: Vec<serde_json::Value>,
850    /// URL to the full community report page
851    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
852    pub web_url: String,
853    /// Key financial metrics extracted from the report
854    pub financial: OperatingFinancial,
855}
856
857/// Key financial metrics extracted from an operating report
858#[derive(Debug, Clone, Serialize, Deserialize)]
859pub struct OperatingFinancial {
860    /// Ticker code (may be empty)
861    pub code: String,
862    /// Symbol in `CODE.MARKET` format (may be empty)
863    pub symbol: String,
864    /// Reporting currency
865    pub currency: String,
866    /// Company name
867    pub name: String,
868    /// Market region
869    pub region: String,
870    /// Report period code
871    pub report: String,
872    /// Report period display text
873    pub report_txt: String,
874    /// Financial indicators
875    pub indicators: Vec<OperatingIndicator>,
876}
877
878/// One financial indicator in an operating report
879#[derive(Debug, Clone, Serialize, Deserialize)]
880pub struct OperatingIndicator {
881    /// Field name key, e.g. `"operating_revenue"`
882    pub field_name: String,
883    /// Display name, e.g. `"营业收入"`
884    pub indicator_name: String,
885    /// Formatted value, e.g. `"8217 亿"`
886    pub indicator_value: String,
887    /// Year-over-year change
888    #[serde(default, with = "crate::serde_utils::decimal_opt_str_is_none")]
889    pub yoy: Option<Decimal>,
890}
891
892// ── buyback ───────────────────────────────────────────────────────
893
894/// Response for [`crate::FundamentalContext::buyback`]
895#[derive(Debug, Clone, Serialize, Deserialize)]
896pub struct BuybackData {
897    /// Most recent buyback summary (TTM)
898    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
899    pub recent_buybacks: Option<RecentBuybacks>,
900    /// Historical annual buyback data
901    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
902    pub buyback_history: Vec<BuybackHistoryItem>,
903    /// Buyback payout and cash-flow ratios
904    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
905    pub buyback_ratios: Vec<BuybackRatios>,
906}
907
908/// TTM (trailing twelve months) buyback summary
909#[derive(Debug, Clone, Serialize, Deserialize)]
910pub struct RecentBuybacks {
911    /// Reporting currency
912    pub currency: String,
913    /// Net buyback amount TTM
914    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
915    pub net_buyback_ttm: Option<Decimal>,
916    /// Net buyback yield TTM
917    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
918    pub net_buyback_yield_ttm: Option<Decimal>,
919}
920
921/// Historical annual buyback data point
922#[derive(Debug, Clone, Serialize, Deserialize)]
923pub struct BuybackHistoryItem {
924    /// Fiscal year label, e.g. `"FY2024"`
925    pub fiscal_year: String,
926    /// Fiscal year date range string
927    pub fiscal_year_range: String,
928    /// Net buyback amount
929    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
930    pub net_buyback: Option<Decimal>,
931    /// Net buyback yield
932    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
933    pub net_buyback_yield: Option<Decimal>,
934    /// Year-over-year net buyback growth rate
935    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
936    pub net_buyback_growth_rate: Option<Decimal>,
937    /// Reporting currency
938    pub currency: String,
939}
940
941/// Buyback payout and cash-flow ratios
942#[derive(Debug, Clone, Serialize, Deserialize)]
943pub struct BuybackRatios {
944    /// Net buyback payout ratio
945    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
946    pub net_buyback_payout_ratio: Option<Decimal>,
947    /// Net buyback to free cash-flow ratio
948    #[serde(with = "crate::serde_utils::decimal_opt_str_is_none")]
949    pub net_buyback_to_cashflow_ratio: Option<Decimal>,
950}
951
952// ── ratings ───────────────────────────────────────────────────────
953
954/// Response for [`crate::FundamentalContext::ratings`]
955#[derive(Debug, Clone, Serialize, Deserialize)]
956pub struct StockRatings {
957    /// Style display name
958    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
959    pub style_txt_name: String,
960    /// Scale display name
961    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
962    pub scale_txt_name: String,
963    /// Report period display text
964    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
965    pub report_period_txt: String,
966    /// Composite score
967    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
968    pub multi_score: Option<f64>,
969    /// Composite score letter grade
970    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
971    pub multi_letter: String,
972    /// Score change vs previous period
973    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
974    pub multi_score_change: i32,
975    /// Industry name
976    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
977    pub industry_name: String,
978    /// Industry rank
979    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
980    pub industry_rank: Option<i64>,
981    /// Total securities in the industry
982    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
983    pub industry_total: Option<i64>,
984    /// Industry mean score
985    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
986    pub industry_mean_score: Option<f64>,
987    /// Industry median score
988    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
989    pub industry_median_score: Option<f64>,
990    /// Detailed rating categories
991    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
992    pub ratings: Vec<RatingCategory>,
993}
994
995/// One rating category (e.g. growth, profitability)
996#[derive(Debug, Clone, Serialize, Deserialize)]
997pub struct RatingCategory {
998    /// Category type code
999    #[serde(rename = "type")]
1000    pub kind: i32,
1001    /// Sub-indicator groups within this category
1002    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1003    pub sub_indicators: Vec<RatingSubIndicatorGroup>,
1004}
1005
1006/// A group of sub-indicators under one category indicator
1007#[derive(Debug, Clone, Serialize, Deserialize)]
1008pub struct RatingSubIndicatorGroup {
1009    /// Parent indicator for this group
1010    pub indicator: RatingIndicator,
1011    /// Leaf sub-indicators
1012    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1013    pub sub_indicators: Vec<RatingLeafIndicator>,
1014}
1015
1016/// A rating indicator node (may be a parent or a leaf)
1017#[derive(Debug, Clone, Serialize, Deserialize)]
1018pub struct RatingIndicator {
1019    /// Indicator display name
1020    pub name: String,
1021    /// Score
1022    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1023    pub score: Option<f64>,
1024    /// Letter grade
1025    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1026    pub letter: String,
1027}
1028
1029/// A leaf rating indicator with a raw value
1030#[derive(Debug, Clone, Serialize, Deserialize)]
1031pub struct RatingLeafIndicator {
1032    /// Indicator display name
1033    pub name: String,
1034    /// Formatted value string
1035    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1036    pub value: String,
1037    /// Value type hint, e.g. `"percent"`
1038    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1039    pub value_type: String,
1040    /// Score
1041    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1042    pub score: Option<f64>,
1043    /// Letter grade
1044    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1045    pub letter: String,
1046}
1047
1048// ── enums ─────────────────────────────────────────────────────────
1049
1050/// Institutional analyst recommendation
1051#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
1052pub enum InstitutionRecommend {
1053    /// Unknown
1054    Unknown,
1055    /// Strong buy
1056    #[strum(serialize = "strong_buy")]
1057    StrongBuy,
1058    /// Buy
1059    #[strum(serialize = "buy")]
1060    Buy,
1061    /// Hold
1062    #[strum(serialize = "hold")]
1063    Hold,
1064    /// Sell
1065    #[strum(serialize = "sell")]
1066    Sell,
1067    /// Strong sell
1068    #[strum(serialize = "strong_sell")]
1069    StrongSell,
1070    /// Underperform
1071    #[strum(serialize = "underperform")]
1072    Underperform,
1073    /// No opinion
1074    #[strum(serialize = "no_opinion")]
1075    NoOpinion,
1076}
1077
1078impl_default_for_enum_string!(InstitutionRecommend);
1079impl_serde_for_enum_string!(InstitutionRecommend);
1080
1081/// Financial report kind
1082#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, Default)]
1083pub enum FinancialReportKind {
1084    /// Income statement
1085    #[serde(rename = "IS")]
1086    IncomeStatement,
1087    /// Balance sheet
1088    #[serde(rename = "BS")]
1089    BalanceSheet,
1090    /// Cash flow statement
1091    #[serde(rename = "CF")]
1092    CashFlow,
1093    /// All statements
1094    #[default]
1095    #[serde(rename = "ALL")]
1096    All,
1097}
1098
1099/// Financial statement kind
1100///
1101/// Used by [`crate::FundamentalContext::us_financial_statement`], which needs
1102/// exactly one statement per request.  Unlike [`FinancialReportKind`] there is
1103/// deliberately no `All` variant and no `Default`: the endpoint answers with an
1104/// empty list for `ALL` (and for a missing `kind`), so a default would silently
1105/// return nothing.
1106#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
1107pub enum FinancialStatementKind {
1108    /// Income statement
1109    #[serde(rename = "IS")]
1110    IncomeStatement,
1111    /// Balance sheet
1112    #[serde(rename = "BS")]
1113    BalanceSheet,
1114    /// Cash flow statement
1115    #[serde(rename = "CF")]
1116    CashFlow,
1117}
1118
1119impl FinancialStatementKind {
1120    /// The value sent as the `kind` query parameter.
1121    #[inline]
1122    pub fn as_str(&self) -> &'static str {
1123        match self {
1124            FinancialStatementKind::IncomeStatement => "IS",
1125            FinancialStatementKind::BalanceSheet => "BS",
1126            FinancialStatementKind::CashFlow => "CF",
1127        }
1128    }
1129}
1130
1131/// Ranking indicator for [`crate::FundamentalContext::industry_rank`]
1132#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
1133pub enum IndustryRankIndicator {
1134    /// Leading gainer
1135    #[serde(rename = "leading-gainer")]
1136    LeadingGainer,
1137    /// Today's trend
1138    #[serde(rename = "today-trend")]
1139    TodayTrend,
1140    /// Popularity
1141    #[serde(rename = "popularity")]
1142    Popularity,
1143    /// Market capitalisation
1144    #[serde(rename = "market-cap")]
1145    MarketCap,
1146    /// Revenue
1147    #[serde(rename = "revenue")]
1148    Revenue,
1149    /// Revenue growth
1150    #[serde(rename = "revenue-growth")]
1151    RevenueGrowth,
1152    /// Net profit
1153    #[serde(rename = "net-profit")]
1154    NetProfit,
1155    /// Net profit growth
1156    #[serde(rename = "net-profit-growth")]
1157    NetProfitGrowth,
1158}
1159
1160impl IndustryRankIndicator {
1161    /// The value sent as the `indicator` query parameter.
1162    #[inline]
1163    pub fn as_str(&self) -> &'static str {
1164        match self {
1165            IndustryRankIndicator::LeadingGainer => "leading-gainer",
1166            IndustryRankIndicator::TodayTrend => "today-trend",
1167            IndustryRankIndicator::Popularity => "popularity",
1168            IndustryRankIndicator::MarketCap => "market-cap",
1169            IndustryRankIndicator::Revenue => "revenue",
1170            IndustryRankIndicator::RevenueGrowth => "revenue-growth",
1171            IndustryRankIndicator::NetProfit => "net-profit",
1172            IndustryRankIndicator::NetProfitGrowth => "net-profit-growth",
1173        }
1174    }
1175}
1176
1177/// Sort mode for [`crate::FundamentalContext::industry_rank`]
1178#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
1179pub enum IndustryRankSortType {
1180    /// Rank by the single selected indicator
1181    #[serde(rename = "single")]
1182    Single,
1183    /// Rank by a composite of several indicators
1184    #[serde(rename = "multi")]
1185    Multi,
1186}
1187
1188impl IndustryRankSortType {
1189    /// The value sent as the `sort_type` query parameter.
1190    #[inline]
1191    pub fn as_str(&self) -> &'static str {
1192        match self {
1193            IndustryRankSortType::Single => "single",
1194            IndustryRankSortType::Multi => "multi",
1195        }
1196    }
1197}
1198
1199// ── business_segments ─────────────────────────────────────────────
1200
1201/// Response for [`crate::FundamentalContext::business_segments`]
1202#[derive(Debug, Clone, Serialize, Deserialize)]
1203pub struct BusinessSegments {
1204    /// Report date
1205    pub date: String,
1206    /// Total revenue
1207    pub total: String,
1208    /// Reporting currency
1209    pub currency: String,
1210    /// Business segment breakdown
1211    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1212    pub business: Vec<BusinessSegmentItem>,
1213}
1214
1215/// One business segment item (latest snapshot)
1216#[derive(Debug, Clone, Serialize, Deserialize)]
1217pub struct BusinessSegmentItem {
1218    /// Segment name
1219    pub name: String,
1220    /// Percentage of total revenue
1221    pub percent: String,
1222}
1223
1224/// Response for [`crate::FundamentalContext::business_segments_history`]
1225#[derive(Debug, Clone, Serialize, Deserialize)]
1226pub struct BusinessSegmentsHistory {
1227    /// Historical snapshots
1228    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1229    pub historical: Vec<BusinessSegmentsHistoricalItem>,
1230}
1231
1232/// One historical business segments snapshot
1233#[derive(Debug, Clone, Serialize, Deserialize)]
1234pub struct BusinessSegmentsHistoricalItem {
1235    /// Report date
1236    pub date: String,
1237    /// Total revenue
1238    pub total: String,
1239    /// Reporting currency
1240    pub currency: String,
1241    /// Business segment breakdown
1242    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1243    pub business: Vec<BusinessSegmentHistoryItem>,
1244    /// Regional breakdown
1245    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1246    pub regionals: Vec<BusinessSegmentHistoryItem>,
1247}
1248
1249/// One business/regional segment item in a historical snapshot
1250#[derive(Debug, Clone, Serialize, Deserialize)]
1251pub struct BusinessSegmentHistoryItem {
1252    /// Segment name
1253    pub name: String,
1254    /// Percentage of total
1255    pub percent: String,
1256    /// Absolute value
1257    pub value: String,
1258}
1259
1260// ── institution_rating_views ──────────────────────────────────────
1261
1262/// Response for [`crate::FundamentalContext::institution_rating_views`]
1263#[derive(Debug, Clone, Serialize, Deserialize)]
1264pub struct InstitutionRatingViews {
1265    /// Historical rating distribution snapshots
1266    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1267    pub elist: Vec<InstitutionRatingViewItem>,
1268}
1269
1270/// One historical rating distribution snapshot
1271#[derive(Debug, Clone, Serialize, Deserialize)]
1272pub struct InstitutionRatingViewItem {
1273    /// Date as unix timestamp string (API returns as quoted or bare integer)
1274    pub date: String,
1275    /// Number of "Buy" ratings (API returns as string)
1276    pub buy: String,
1277    /// Number of "Outperform" ratings (API returns as string)
1278    pub over: String,
1279    /// Number of "Hold" ratings (API returns as string)
1280    pub hold: String,
1281    /// Number of "Underperform" ratings (API returns as string)
1282    pub under: String,
1283    /// Number of "Sell" ratings (API returns as string)
1284    pub sell: String,
1285    /// Total analyst count (API returns as string)
1286    pub total: String,
1287}
1288
1289// ── industry_rank ─────────────────────────────────────────────────
1290
1291/// Response for [`crate::FundamentalContext::industry_rank`]
1292#[derive(Debug, Clone, Serialize, Deserialize)]
1293pub struct IndustryRankResponse {
1294    /// Grouped rank items
1295    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1296    pub items: Vec<IndustryRankGroup>,
1297}
1298
1299/// A group of ranked industry items
1300#[derive(Debug, Clone, Serialize, Deserialize)]
1301pub struct IndustryRankGroup {
1302    /// Items in this group
1303    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1304    pub lists: Vec<IndustryRankItem>,
1305}
1306
1307/// One ranked industry item
1308#[derive(Debug, Clone, Serialize, Deserialize)]
1309pub struct IndustryRankItem {
1310    /// Industry / sector name
1311    pub name: String,
1312    /// Industry symbol
1313    pub symbol: String,
1314    /// Change percentage
1315    pub chg: String,
1316    /// Name of the leading stock
1317    pub leading_name: String,
1318    /// Ticker of the leading stock
1319    pub leading_ticker: String,
1320    /// Change percentage of the leading stock
1321    pub leading_chg: String,
1322    /// Value label name
1323    pub value_name: String,
1324    /// Value data
1325    pub value_data: String,
1326}
1327
1328// ── industry_peers ────────────────────────────────────────────────
1329
1330/// Response for [`crate::FundamentalContext::industry_peers`]
1331#[derive(Debug, Clone, Serialize, Deserialize)]
1332pub struct IndustryPeersResponse {
1333    /// Top-level industry node info (may be absent if no data)
1334    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1335    pub top: Option<IndustryPeersTop>,
1336    /// Root peer chain node (may be absent if no data)
1337    pub chain: Option<IndustryPeerNode>,
1338}
1339
1340/// Top-level industry info in the peers response
1341#[derive(Debug, Clone, Serialize, Deserialize)]
1342pub struct IndustryPeersTop {
1343    /// Industry name
1344    pub name: String,
1345    /// Market code
1346    pub market: String,
1347}
1348
1349/// A node in the recursive industry peer chain
1350#[derive(Debug, Clone, Serialize, Deserialize)]
1351pub struct IndustryPeerNode {
1352    /// Node name
1353    pub name: String,
1354    /// Node symbol
1355    pub symbol: String,
1356    /// Number of stocks in this node (API returns as integer)
1357    pub stock_num: i32,
1358    /// Change percentage
1359    pub chg: String,
1360    /// Year-to-date change
1361    pub ytd_chg: String,
1362    /// Child nodes (recursive)
1363    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1364    pub next: Vec<IndustryPeerNode>,
1365}
1366
1367// ── financial_report_snapshot ─────────────────────────────────────
1368
1369/// Response for [`crate::FundamentalContext::financial_report_snapshot`]
1370#[derive(Debug, Clone, Serialize, Deserialize)]
1371pub struct FinancialReportSnapshot {
1372    /// Company name
1373    pub name: String,
1374    /// Ticker code
1375    pub ticker: String,
1376    /// Fiscal period start date
1377    pub fp_start: String,
1378    /// Fiscal period end date
1379    pub fp_end: String,
1380    /// Reporting currency
1381    pub currency: String,
1382    /// Report description
1383    pub report_desc: String,
1384    /// Forecast revenue
1385    pub fo_revenue: Option<SnapshotForecastMetric>,
1386    /// Forecast EBIT
1387    pub fo_ebit: Option<SnapshotForecastMetric>,
1388    /// Forecast EPS
1389    pub fo_eps: Option<SnapshotForecastMetric>,
1390    /// Reported revenue
1391    pub fr_revenue: Option<SnapshotReportedMetric>,
1392    /// Reported net profit
1393    pub fr_profit: Option<SnapshotReportedMetric>,
1394    /// Reported operating cash flow
1395    pub fr_operate_cash: Option<SnapshotReportedMetric>,
1396    /// Reported investing cash flow
1397    pub fr_invest_cash: Option<SnapshotReportedMetric>,
1398    /// Reported financing cash flow
1399    pub fr_finance_cash: Option<SnapshotReportedMetric>,
1400    /// Reported total assets
1401    pub fr_total_assets: Option<SnapshotReportedMetric>,
1402    /// Reported total liabilities
1403    pub fr_total_liability: Option<SnapshotReportedMetric>,
1404    /// ROE TTM
1405    pub fr_roe_ttm: String,
1406    /// Profit margin
1407    pub fr_profit_margin: String,
1408    /// Profit margin TTM
1409    pub fr_profit_margin_ttm: String,
1410    /// Asset turnover TTM
1411    pub fr_asset_turn_ttm: String,
1412    /// Leverage TTM
1413    pub fr_leverage_ttm: String,
1414    /// Debt-to-assets ratio
1415    pub fr_debt_assets_ratio: String,
1416}
1417
1418/// A forecast metric in the financial report snapshot
1419#[derive(Debug, Clone, Serialize, Deserialize)]
1420pub struct SnapshotForecastMetric {
1421    /// Actual value
1422    pub value: String,
1423    /// Year-over-year change
1424    pub yoy: String,
1425    /// Beat/miss description
1426    pub cmp_desc: String,
1427    /// Consensus estimate value
1428    pub est_value: String,
1429}
1430
1431/// A reported metric in the financial report snapshot
1432#[derive(Debug, Clone, Serialize, Deserialize)]
1433pub struct SnapshotReportedMetric {
1434    /// Actual value
1435    pub value: String,
1436    /// Year-over-year change
1437    pub yoy: String,
1438}
1439
1440// ── shareholder_top ───────────────────────────────────────────────
1441
1442/// Response for [`crate::FundamentalContext::shareholder_top`]
1443#[derive(Debug, Clone, Serialize, Deserialize)]
1444pub struct ShareholderTopResponse {
1445    /// Raw top-shareholder data
1446    pub data: serde_json::Value,
1447}
1448
1449// ── shareholder_detail ────────────────────────────────────────────
1450
1451/// Response for [`crate::FundamentalContext::shareholder_detail`]
1452#[derive(Debug, Clone, Serialize, Deserialize)]
1453pub struct ShareholderDetailResponse {
1454    /// Raw shareholder detail data
1455    pub data: serde_json::Value,
1456}
1457
1458// ── valuation_comparison ──────────────────────────────────────────
1459
1460/// One historical valuation data point.
1461#[derive(Debug, Clone, Serialize, Deserialize)]
1462pub struct ValuationHistoryPoint {
1463    /// Date (RFC 3339, converted from Unix timestamp)
1464    pub date: String,
1465    /// P/E ratio
1466    pub pe: String,
1467    /// P/B ratio
1468    pub pb: String,
1469    /// P/S ratio
1470    pub ps: String,
1471}
1472
1473/// One security's valuation comparison item.
1474#[derive(Debug, Clone, Serialize, Deserialize)]
1475pub struct ValuationComparisonItem {
1476    /// Symbol
1477    pub symbol: String,
1478    /// Security name
1479    pub name: String,
1480    /// Currency
1481    pub currency: String,
1482    /// Market capitalisation
1483    pub market_value: String,
1484    /// Latest closing price
1485    pub price_close: String,
1486    /// P/E ratio
1487    pub pe: String,
1488    /// P/B ratio
1489    pub pb: String,
1490    /// P/S ratio
1491    pub ps: String,
1492    /// Return on equity
1493    pub roe: String,
1494    /// Earnings per share
1495    pub eps: String,
1496    /// Book value per share
1497    pub bps: String,
1498    /// Dividends per share
1499    pub dps: String,
1500    /// Dividend yield
1501    pub div_yld: String,
1502    /// Total assets
1503    pub assets: String,
1504    /// Historical valuation points
1505    pub history: Vec<ValuationHistoryPoint>,
1506}
1507
1508/// Response for [`crate::FundamentalContext::valuation_comparison`]
1509#[derive(Debug, Clone, Serialize, Deserialize)]
1510pub struct ValuationComparisonResponse {
1511    /// Valuation comparison items
1512    pub list: Vec<ValuationComparisonItem>,
1513}
1514
1515/// Financial report period type
1516#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
1517pub enum FinancialReportPeriod {
1518    /// Annual report
1519    #[serde(rename = "af")]
1520    Annual,
1521    /// Semi-annual report
1522    #[serde(rename = "saf")]
1523    SemiAnnual,
1524    /// Q1 report
1525    #[serde(rename = "q1")]
1526    Q1,
1527    /// Q2 report
1528    #[serde(rename = "q2")]
1529    Q2,
1530    /// Q3 report
1531    #[serde(rename = "q3")]
1532    Q3,
1533    /// Full quarterly report
1534    #[serde(rename = "qf")]
1535    QuarterlyFull,
1536    /// Three-quarter report (first three quarters)
1537    #[serde(rename = "3q")]
1538    ThreeQ,
1539}
1540
1541// ── etf_asset_allocation ──────────────────────────────────────────
1542
1543/// ETF asset allocation element type
1544#[derive(Debug, FromPrimitive, IntoPrimitive, Copy, Clone, Hash, Eq, PartialEq)]
1545#[repr(i32)]
1546pub enum ElementType {
1547    /// Unknown
1548    #[num_enum(default)]
1549    Unknown = 0,
1550    /// Holdings
1551    Holdings = 1,
1552    /// Regional
1553    Regional = 2,
1554    /// Asset class
1555    AssetClass = 3,
1556    /// Industry
1557    Industry = 4,
1558}
1559
1560impl Serialize for ElementType {
1561    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1562    where
1563        S: serde::Serializer,
1564    {
1565        serializer.serialize_i32((*self).into())
1566    }
1567}
1568
1569impl<'de> Deserialize<'de> for ElementType {
1570    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1571    where
1572        D: serde::Deserializer<'de>,
1573    {
1574        Ok(ElementType::from(i32::deserialize(deserializer)?))
1575    }
1576}
1577
1578/// Holding detail of an ETF asset allocation element (holdings only)
1579#[derive(Debug, Clone, Serialize, Deserialize)]
1580pub struct HoldingDetail {
1581    /// Industry ID
1582    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1583    pub industry_id: String,
1584    /// Industry name
1585    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1586    pub industry_name: String,
1587    /// Index counter ID (e.g. `BK/US/CP99000`)
1588    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1589    pub index: String,
1590    /// Index name
1591    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1592    pub index_name: String,
1593    /// Holding type (e.g. `E` for stock)
1594    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1595    pub holding_type: String,
1596    /// Holding type name
1597    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1598    pub holding_type_name: String,
1599}
1600
1601/// One element of an ETF asset allocation group
1602#[derive(Debug, Clone, Serialize, Deserialize)]
1603pub struct AssetAllocationItem {
1604    /// Element name
1605    pub name: String,
1606    /// Security code (holdings only, e.g. `NVDA`)
1607    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1608    pub code: String,
1609    /// Position ratio (e.g. `0.0861114`)
1610    pub position_ratio: String,
1611    /// Security symbol (holdings only, e.g. `NVDA.US`)
1612    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1613    pub symbol: String,
1614    /// Localized names (locale → name, e.g. `zh-CN` → `英伟达`)
1615    #[serde(rename = "name_locales_map", default)]
1616    pub name_locales: HashMap<String, String>,
1617    /// Holding detail (holdings only)
1618    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1619    pub holding_detail: Option<HoldingDetail>,
1620}
1621
1622/// One ETF asset allocation group (grouped by element type)
1623#[derive(Debug, Clone, Serialize, Deserialize)]
1624pub struct AssetAllocationGroup {
1625    /// Report date (e.g. `20260601`)
1626    pub report_date: String,
1627    /// Element type of this group
1628    pub asset_type: ElementType,
1629    /// Elements
1630    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1631    pub lists: Vec<AssetAllocationItem>,
1632}
1633
1634/// Response for [`crate::FundamentalContext::etf_asset_allocation`]
1635#[derive(Debug, Clone, Serialize, Deserialize)]
1636pub struct AssetAllocationResponse {
1637    /// Asset allocation groups
1638    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1639    pub info: Vec<AssetAllocationGroup>,
1640}
1641
1642// ── macroeconomic ─────────────────────────────────────────────────────
1643
1644/// Country for filtering macroeconomic indicators
1645#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
1646pub enum MacroeconomicCountry {
1647    /// Hong Kong SAR China
1648    #[serde(rename = "Hong Kong SAR China")]
1649    HongKong,
1650    /// China (Mainland)
1651    #[serde(rename = "China (Mainland)")]
1652    China,
1653    /// United States
1654    #[serde(rename = "United States")]
1655    UnitedStates,
1656    /// Euro Zone
1657    #[serde(rename = "Euro Zone")]
1658    EuroZone,
1659    /// Japan
1660    #[serde(rename = "Japan")]
1661    Japan,
1662    /// Singapore
1663    #[serde(rename = "Singapore")]
1664    Singapore,
1665}
1666
1667/// Importance level of a macroeconomic indicator
1668#[derive(Debug, Copy, Clone, Eq, PartialEq)]
1669pub enum MacroeconomicImportance {
1670    /// Low importance
1671    Low = 1,
1672    /// Medium importance
1673    Medium = 2,
1674    /// High importance
1675    High = 3,
1676}
1677
1678impl MacroeconomicImportance {
1679    /// Convert from raw API integer value
1680    pub fn from_i32(v: i32) -> Option<Self> {
1681        match v {
1682            1 => Some(Self::Low),
1683            2 => Some(Self::Medium),
1684            3 => Some(Self::High),
1685            _ => None,
1686        }
1687    }
1688}
1689
1690/// Localized text in simplified Chinese, traditional Chinese, and English
1691#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1692pub struct MultiLanguageText {
1693    /// English
1694    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1695    pub english: String,
1696    /// Simplified Chinese
1697    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1698    pub simplified_chinese: String,
1699    /// Traditional Chinese
1700    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1701    pub traditional_chinese: String,
1702}
1703
1704/// Metadata for one macroeconomic indicator
1705#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1706pub struct MacroeconomicIndicator {
1707    /// External vendor code (used as input to `macroeconomic`)
1708    pub indicator_code: String,
1709    /// Publishing organisation
1710    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1711    pub source_org: String,
1712    /// Country
1713    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1714    pub country: String,
1715    /// Indicator name
1716    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1717    pub name: String,
1718    /// Adjustment factor
1719    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1720    pub adjustment_factor: String,
1721    /// Release periodicity (e.g. `monthly` / `quarterly`)
1722    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1723    pub periodicity: String,
1724    /// Indicator category
1725    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1726    pub category: String,
1727    /// Description
1728    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1729    pub describe: String,
1730    /// Importance — higher is more important
1731    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1732    pub importance: i32,
1733    /// Start date of data coverage
1734    #[serde(
1735        default,
1736        with = "crate::serde_utils::rfc3339_opt",
1737        rename = "start_date"
1738    )]
1739    pub start_date: Option<OffsetDateTime>,
1740}
1741
1742/// Response for [`crate::FundamentalContext::macroeconomic_indicators`]
1743#[derive(Debug, Clone, Serialize, Deserialize)]
1744pub struct MacroeconomicIndicatorListResponse {
1745    /// Indicator list
1746    #[serde(
1747        default,
1748        deserialize_with = "crate::serde_utils::null_as_default",
1749        rename = "list"
1750    )]
1751    pub data: Vec<MacroeconomicIndicator>,
1752    /// Total number of indicators matching the query
1753    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1754    pub count: i32,
1755}
1756
1757/// One historical data point for a macroeconomic indicator
1758#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1759pub struct Macroeconomic {
1760    /// Statistical period (e.g. `2024-Q1`, `2024-03`)
1761    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1762    pub period: String,
1763    /// Release datetime
1764    #[serde(default, with = "crate::serde_utils::rfc3339_opt")]
1765    pub release_at: Option<OffsetDateTime>,
1766    /// Actual value
1767    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1768    pub actual_value: String,
1769    /// Previous value
1770    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1771    pub previous_value: String,
1772    /// Forecast value (market consensus)
1773    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1774    pub forecast_value: String,
1775    /// Revised value
1776    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1777    pub revised_value: String,
1778    /// Next release datetime
1779    #[serde(default, with = "crate::serde_utils::rfc3339_opt")]
1780    pub next_release_at: Option<OffsetDateTime>,
1781    /// Unit
1782    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1783    pub unit: String,
1784    /// Unit prefix / data scale (e.g. millions / billions)
1785    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1786    pub unit_prefix: String,
1787}
1788
1789/// Response for [`crate::FundamentalContext::macroeconomic`]
1790#[derive(Debug, Clone, Serialize, Deserialize)]
1791pub struct MacroeconomicResponse {
1792    /// Indicator metadata
1793    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1794    pub info: MacroeconomicIndicator,
1795    /// Historical data points
1796    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1797    pub data: Vec<Macroeconomic>,
1798    /// Total number of historical data points
1799    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1800    pub count: i32,
1801}
1802
1803// ── US-market types
1804// ───────────────────────────────────────────────────────────
1805
1806/// Industry rank tag returned by
1807/// [`crate::FundamentalContext::us_company_overview`].
1808#[derive(Debug, Clone, Serialize, Deserialize)]
1809pub struct USRankTag {
1810    /// Tag key
1811    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1812    pub key: String,
1813    /// Display position / ordering
1814    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1815    pub location: i32,
1816    /// Tag title
1817    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1818    pub title: String,
1819    /// Tag text
1820    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1821    pub text: String,
1822    /// Rank type code
1823    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1824    pub rank_type: i32,
1825    /// Highlighted portion of the text
1826    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1827    pub highlight_text: String,
1828}
1829
1830/// One entry in [`USCompanyOverview`]'s sharelist field.
1831#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1832pub struct USSharelistItem {
1833    /// Price change ratio
1834    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1835    pub chg: String,
1836    /// Sharelist ID
1837    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1838    pub id: String,
1839    /// Sharelist name
1840    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1841    pub name: String,
1842}
1843
1844/// Response for [`crate::FundamentalContext::us_company_overview`].
1845#[derive(Debug, Clone, Serialize, Deserialize)]
1846pub struct USCompanyOverview {
1847    /// Company introduction / description
1848    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1849    pub intro: String,
1850    /// Market capitalisation
1851    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1852    pub market_cap: String,
1853    /// Currency symbol (e.g. `"$"`)
1854    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1855    pub ccy_symbol: String,
1856    /// Top industry-rank tags
1857    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1858    pub top_rank_tags: Vec<USRankTag>,
1859    /// Detail page URL
1860    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1861    pub detail_url: String,
1862    /// Related sharelists
1863    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1864    pub share_list: Vec<USSharelistItem>,
1865}
1866
1867/// One valuation metric entry within [`USValuationOverview`].
1868#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1869pub struct USValuationMetric {
1870    /// Position on the percentile circle / gauge
1871    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1872    pub circle: String,
1873    /// Segment / part label
1874    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1875    pub part: String,
1876    /// Metric value
1877    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1878    pub metric: String,
1879    /// Metric description
1880    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1881    pub desc: String,
1882    /// Industry median for this metric
1883    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1884    pub industry_median: String,
1885}
1886
1887/// Response for [`crate::FundamentalContext::us_valuation_overview`].
1888#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1889pub struct USValuationOverview {
1890    /// Map of metric key (e.g. "pe") to its valuation data
1891    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1892    pub metrics: std::collections::HashMap<String, USValuationMetric>,
1893    /// Active indicator key (e.g. "pe")
1894    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1895    pub indicator: String,
1896    /// Historical percentile range in years
1897    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1898    pub range: i32,
1899    /// Data date string
1900    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1901    pub date: String,
1902    /// Currency symbol (e.g. `"$"`)
1903    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1904    pub ccy_symbol: String,
1905    /// Embedded AI-chat context
1906    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1907    pub aichat_data: USAIChatData,
1908    /// AI-generated summary text
1909    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1910    pub ai_summary: String,
1911}
1912
1913/// One financial field within a [`USFinancialStatementPeriod`].
1914#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1915pub struct USFinancialStatementField {
1916    /// Display order within the statement
1917    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1918    pub display_order: i32,
1919    /// Field code
1920    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1921    pub field: String,
1922    /// Field ID
1923    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1924    pub id: String,
1925    /// Nesting level (for indentation)
1926    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1927    pub level: i64,
1928    /// Field display name
1929    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1930    pub name: String,
1931    /// Field value
1932    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1933    pub value: String,
1934    /// Value type hint
1935    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1936    pub value_type: String,
1937    /// Year-over-year change
1938    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1939    pub yoy: String,
1940}
1941
1942/// One reporting period in [`USFinancialStatement`].
1943#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1944pub struct USFinancialStatementPeriod {
1945    /// Fiscal period (e.g. `"Q1"`, `"FY"`)
1946    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1947    pub ff_period: String,
1948    /// Fiscal year
1949    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1950    pub ff_year: i32,
1951    /// Statement fields for this period
1952    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1953    pub fields: Vec<USFinancialStatementField>,
1954    /// Fiscal-period end date
1955    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1956    pub fp_end: String,
1957    /// Report label text
1958    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1959    pub report_txt: String,
1960    /// Report publication date
1961    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1962    pub rpt_date: String,
1963}
1964
1965/// Response for [`crate::FundamentalContext::us_financial_statement`].
1966#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1967pub struct USFinancialStatement {
1968    /// Reporting currency
1969    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1970    pub currency: String,
1971    /// Report type
1972    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1973    pub report: String,
1974    /// Per-period statement data
1975    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1976    pub list: Vec<USFinancialStatementPeriod>,
1977    /// Field codes that have no data
1978    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1979    pub empty_fields: Vec<String>,
1980}
1981
1982/// Per-fiscal-year dividend records for a US ETF.
1983#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1984pub struct USFiscalYearDividend {
1985    /// Dividend amount for the fiscal year
1986    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1987    pub dividend: String,
1988    /// Dividend yield for the fiscal year
1989    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1990    pub dividend_yield: String,
1991    /// Fiscal year
1992    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1993    pub fiscal_year: String,
1994    /// Currency
1995    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1996    pub currency: String,
1997    /// Fiscal-year date range
1998    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1999    pub fiscal_year_range: String,
2000}
2001
2002/// Response for [`crate::FundamentalContext::us_etf_dividend_info`].
2003#[derive(Debug, Clone, Serialize, Deserialize)]
2004pub struct USETFDividendInfo {
2005    /// Total dividend over trailing 12 months
2006    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2007    pub dividend_ttm: String,
2008    /// Dividend yield over trailing 12 months
2009    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2010    pub dividend_yield_ttm: String,
2011    /// Dividend frequency
2012    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2013    pub dividend_frequency: String,
2014    /// Currency
2015    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2016    pub currency: String,
2017    /// Per-fiscal-year dividend records
2018    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2019    pub fiscal_year_info: Vec<USFiscalYearDividend>,
2020}
2021
2022/// A single historical dividend payment.
2023#[derive(Debug, Clone, Serialize, Deserialize)]
2024pub struct USDividendItem {
2025    /// Per-share dividend amount
2026    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2027    pub dividend: String,
2028    /// Dividend type (e.g. cash dividend)
2029    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2030    pub dividend_type: String,
2031    /// Ex-dividend date
2032    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2033    pub ex_date: String,
2034    /// Payment date
2035    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2036    pub payment_date: String,
2037    /// Record date
2038    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2039    pub record_date: String,
2040}
2041
2042/// Trailing-12-month dividend summary within [`USCompanyDividends`].
2043#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2044pub struct USRecentDividend {
2045    /// Total dividend over the trailing 12 months
2046    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2047    pub dividend_ttm: String,
2048    /// Dividend yield over the trailing 12 months
2049    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2050    pub dividend_yield_ttm: String,
2051    /// Number of payouts
2052    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2053    pub payouts: String,
2054    /// Currency
2055    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2056    pub currency: String,
2057}
2058
2059/// One fiscal-year row in the dividend history or payout-ratio table.
2060#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2061pub struct USDividendHistoryItem {
2062    /// Fiscal year
2063    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2064    pub fiscal_year: String,
2065    /// Fiscal-year date range
2066    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2067    pub fiscal_year_range: String,
2068    /// Total shareholder yield (dividend + buyback)
2069    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2070    pub total_shareholder_yield: String,
2071    /// Dividend amount
2072    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2073    pub dividend: String,
2074    /// Dividend yield
2075    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2076    pub dividend_yield: String,
2077    /// Dividend growth rate
2078    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2079    pub dividend_growth_rate: String,
2080    /// Dividend payout ratio
2081    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2082    pub dividend_payout_ratio: String,
2083    /// Dividend-to-cash-flow ratio
2084    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2085    pub dividend_to_cashflow_ratio: String,
2086    /// Net buyback amount
2087    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2088    pub net_buyback: String,
2089    /// Net buyback yield
2090    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2091    pub net_buyback_yield: String,
2092    /// Net buyback growth rate
2093    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2094    pub net_buyback_growth_rate: String,
2095    /// Net buyback payout ratio
2096    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2097    pub net_buyback_payout_ratio: String,
2098    /// Net-buyback-to-cash-flow ratio
2099    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2100    pub net_buyback_to_cashflow_ratio: String,
2101    /// Currency
2102    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2103    pub currency: String,
2104}
2105
2106/// One actual dividend payment event in [`USCompanyDividends`].
2107#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2108pub struct USDividendPayoutRecord {
2109    /// Per-share dividend amount
2110    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2111    pub dividend: String,
2112    /// Dividend type (e.g. cash dividend)
2113    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2114    pub dividend_type: String,
2115    /// Currency
2116    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2117    pub currency: String,
2118    /// Ex-dividend date
2119    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2120    pub ex_date: String,
2121    /// Payment date
2122    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2123    pub payment_date: String,
2124    /// Record date
2125    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2126    pub record_date: String,
2127    /// Display title
2128    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2129    pub title: String,
2130    /// Start time as a Unix-seconds string
2131    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2132    pub start_time_unix: String,
2133}
2134
2135/// Response for [`crate::FundamentalContext::us_company_dividends`].
2136#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2137pub struct USCompanyDividends {
2138    /// Trailing-12-month dividend summary
2139    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2140    pub recent_dividends: USRecentDividend,
2141    /// Per-fiscal-year dividend history
2142    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2143    pub dividend_history: Vec<USDividendHistoryItem>,
2144    /// Per-fiscal-year payout ratios
2145    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2146    pub payout_ratios: Vec<USDividendHistoryItem>,
2147    /// Individual dividend payout events
2148    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2149    pub dividend_payout_history: Vec<USDividendPayoutRecord>,
2150}
2151
2152/// A single file in an ETF document list.
2153#[derive(Debug, Clone, Serialize, Deserialize)]
2154pub struct USETFFile {
2155    /// File name
2156    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2157    pub file_name: String,
2158    /// File path / URL
2159    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2160    pub file_path: String,
2161    /// Last update date
2162    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2163    pub update_date: String,
2164    /// Document type code
2165    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2166    pub code: String,
2167    /// File format (e.g. `"pdf"`)
2168    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2169    pub format: String,
2170}
2171
2172/// Response for [`crate::FundamentalContext::us_etf_files`].
2173#[derive(Debug, Clone, Serialize, Deserialize)]
2174pub struct USETFFilesResponse {
2175    /// List of ETF documents
2176    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2177    pub files: Vec<USETFFile>,
2178}
2179
2180// ── v2 wire types (internal, used for mapping to existing public types) ──────
2181
2182/// v2 wire: one indicator from GET /v2/quote/macrodata
2183#[derive(Debug, Clone, Serialize, Deserialize)]
2184pub(crate) struct V2MacroIndicator {
2185    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2186    pub indicator_id: i32,
2187    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2188    pub indicator_name: String,
2189    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2190    pub market: String,
2191    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2192    pub importance: i32,
2193    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2194    pub description: String,
2195    /// Update frequency: day/week/month/quarter/half_year/year
2196    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2197    pub frequence: String,
2198}
2199
2200/// v2 wire: response from GET /v2/quote/macrodata
2201#[derive(Debug, Clone, Serialize, Deserialize)]
2202pub(crate) struct V2MacroIndicatorListResponse {
2203    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2204    pub indicator_list: Vec<V2MacroIndicator>,
2205    /// Total count for pagination
2206    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2207    pub total: i32,
2208}
2209
2210/// v2 wire: one data point from GET /v2/quote/macrodata/:id
2211#[derive(Debug, Clone, Serialize, Deserialize)]
2212pub(crate) struct V2IndicatorDataDetail {
2213    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2214    pub actual_data: String,
2215    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2216    pub previous_data: String,
2217    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2218    pub estimated_data: String,
2219    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2220    pub published_time: String,
2221    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2222    pub observation_date: String,
2223}
2224
2225/// v2 wire: one indicator with data from GET /v2/quote/macrodata/:id
2226#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2227pub(crate) struct V2MacroIndicatorDetail {
2228    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2229    pub indicator_id: i32,
2230    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2231    pub indicator_name: String,
2232    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2233    pub unit: String,
2234    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2235    pub description: String,
2236    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2237    pub market: String,
2238    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2239    pub frequence: String,
2240    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2241    pub importance: i32,
2242    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2243    pub indicator_data: Vec<V2IndicatorDataDetail>,
2244}
2245
2246/// v2 wire: response from GET /v2/quote/macrodata/:id
2247/// (GetMacroIndicatorHistoryResp)
2248#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2249pub(crate) struct V2MacroIndicatorDataResponse {
2250    /// Single indicator with paginated data points
2251    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2252    pub indicator: V2MacroIndicatorDetail,
2253    /// Total data points matching the query (for pagination)
2254    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2255    pub total: i32,
2256}
2257
2258// ── US financial overview ─────────────────────────────────────────────────
2259
2260/// One reporting-period window shared by IS/BS/CF entries.
2261#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2262pub struct USReportPeriod {
2263    /// Period start date
2264    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2265    pub start_date: String,
2266    /// Period end date
2267    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2268    pub end_date: String,
2269    /// Report label text
2270    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2271    pub report_txt: String,
2272}
2273
2274/// One income-statement entry in [`USFinancialOverview`].
2275#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2276pub struct USFinancialISItem {
2277    /// Revenue
2278    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2279    pub revenue: String,
2280    /// Net income
2281    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2282    pub net_income: String,
2283    /// Net margin
2284    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2285    pub net_margin: String,
2286    /// Reporting period
2287    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2288    pub report: USReportPeriod,
2289}
2290
2291/// One balance-sheet entry in [`USFinancialOverview`].
2292#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2293pub struct USFinancialBSItem {
2294    /// Debt-to-assets ratio
2295    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2296    pub debt_assets_ratio: String,
2297    /// Total assets
2298    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2299    pub total_assets: String,
2300    /// Total liabilities
2301    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2302    pub total_liabilities: String,
2303    /// Reporting period
2304    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2305    pub report: USReportPeriod,
2306}
2307
2308/// One cash-flow entry in [`USFinancialOverview`].
2309#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2310pub struct USFinancialCFItem {
2311    /// Operating cash flow
2312    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2313    pub operating: String,
2314    /// Investing cash flow
2315    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2316    pub investing: String,
2317    /// Financing cash flow
2318    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2319    pub financing: String,
2320    /// Reporting period
2321    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2322    pub report: USReportPeriod,
2323}
2324
2325/// Response for [`crate::FundamentalContext::us_financial_overview`].
2326#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2327pub struct USFinancialOverview {
2328    /// Currency symbol (e.g. `"$"`)
2329    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2330    pub ccy_symbol: String,
2331    /// Report type
2332    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2333    pub report_type: String,
2334    /// Income-statement entries
2335    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2336    pub is_list: Vec<USFinancialISItem>,
2337    /// Balance-sheet entries
2338    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2339    pub bs_list: Vec<USFinancialBSItem>,
2340    /// Cash-flow entries
2341    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2342    pub cf_list: Vec<USFinancialCFItem>,
2343}
2344
2345// ── US key financial metrics ──────────────────────────────────────────────
2346
2347/// One period entry in [`USKeyFinancialMetrics`].
2348#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2349pub struct USKeyMetricItem {
2350    /// Fiscal period (e.g. `"Q1"`, `"FY"`)
2351    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2352    pub ff_period: String,
2353    /// Fiscal year
2354    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2355    pub ff_year: i32,
2356    /// Fiscal-period end date
2357    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2358    pub fp_end: String,
2359    /// Report label text
2360    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2361    pub report_txt: String,
2362    /// Report publication date
2363    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2364    pub rpt_date: String,
2365    /// Metric values — shape varies per field configuration.
2366    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2367    pub fields: Vec<serde_json::Value>,
2368}
2369
2370/// Response for [`crate::FundamentalContext::us_key_financial_metrics`].
2371#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2372pub struct USKeyFinancialMetrics {
2373    /// Reporting currency
2374    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2375    pub currency: String,
2376    /// Report type
2377    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2378    pub report: String,
2379    /// Field codes that have no data
2380    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2381    pub empty_fields: Vec<String>,
2382    /// Per-period metric data
2383    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2384    pub list: Vec<USKeyMetricItem>,
2385}
2386
2387// ── US analyst consensus ──────────────────────────────────────────────────
2388
2389/// AI chat context embedded in [`USAnalystConsensus`].
2390#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2391pub struct USAIChatData {
2392    /// AI agent ID
2393    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2394    pub agent_id: String,
2395    /// Handoff agent ID
2396    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2397    pub handoff_agent_id: String,
2398    /// Security symbol
2399    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2400    pub symbol: String,
2401    /// Prompt / context text
2402    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2403    pub text: String,
2404    /// Chat type
2405    #[serde(
2406        default,
2407        deserialize_with = "crate::serde_utils::null_as_default",
2408        rename = "type"
2409    )]
2410    pub chat_type: String,
2411    /// Workflow type
2412    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2413    pub workflow_type: String,
2414}
2415
2416/// Actual vs estimated value for one consensus metric.
2417#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2418pub struct USConsensusEstimate {
2419    /// Actual reported value
2420    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2421    pub actual: String,
2422    /// Consensus estimate value
2423    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2424    pub estimate: String,
2425}
2426
2427/// One fiscal-year entry in [`USAnalystConsensus`]'s list.
2428#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2429pub struct USConsensusItem {
2430    /// EBIT actual vs estimate
2431    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2432    pub ebit: USConsensusEstimate,
2433    /// EPS actual vs estimate
2434    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2435    pub eps: USConsensusEstimate,
2436    /// Fiscal year
2437    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2438    pub fiscal_year: i64,
2439    /// Report label text
2440    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2441    pub report_txt: String,
2442    /// Revenue actual vs estimate
2443    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2444    pub revenue: USConsensusEstimate,
2445}
2446
2447/// Response for [`crate::FundamentalContext::us_analyst_consensus`].
2448#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2449pub struct USAnalystConsensus {
2450    /// AI-generated summary text
2451    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2452    pub ai_summary: String,
2453    /// Embedded AI-chat context
2454    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2455    pub aichat_data: USAIChatData,
2456    /// Reporting currency
2457    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2458    pub currency: String,
2459    /// Report type
2460    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2461    pub report: String,
2462    /// Per-fiscal-year consensus estimates
2463    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2464    pub list: Vec<USConsensusItem>,
2465    /// Option consensus type identifiers (e.g. "call", "put").
2466    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2467    pub opt_reports: Vec<String>,
2468    /// Raw H5 page data (structure varies)
2469    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2470    pub h5_data: serde_json::Value,
2471}
2472
2473#[cfg(test)]
2474mod tests {
2475    use super::*;
2476
2477    #[test]
2478    fn us_company_dividends_tolerates_null_recent_dividends() {
2479        // The server sends an explicit `"recent_dividends": null` when the
2480        // company has no trailing dividends; `#[serde(default)]` alone only
2481        // covers a missing key.
2482        let parsed: USCompanyDividends = serde_json::from_str(
2483            r#"{"dividend_history":[],"dividend_payout_history":[],"payout_ratios":[],"recent_dividends":null}"#,
2484        )
2485        .unwrap();
2486        assert!(parsed.recent_dividends.dividend_ttm.is_empty());
2487    }
2488
2489    #[test]
2490    fn institution_rating_detail_tolerates_null_series() {
2491        // Symbols without coverage return `"target": null` (and potentially
2492        // `"evaluate": null`); both must map to empty series, not error.
2493        let parsed: InstitutionRatingDetail =
2494            serde_json::from_str(r#"{"ccy_symbol":"HK$","evaluate":null,"target":null}"#).unwrap();
2495        assert!(parsed.target.list.is_empty());
2496        assert!(parsed.evaluate.list.is_empty());
2497    }
2498}