akshare 0.1.2

100% pure Rust implementation of akshare — unified access to Chinese and global financial market data APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! Tonghuashun (THS / 10jqka) fundamental data APIs.
//!
//! Covers: financial statements (abstract, balance, income, cash flow),
//! management/shareholder changes, IPO data, profit forecasts,
//! and main business introduction.

use std::collections::HashMap;
use std::sync::LazyLock;

use crate::client::AkShareClient;
use crate::error::{Error, Result};

static RE_HTML_TAG: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"<[^>]+>").unwrap());
static RE_TABLE: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"(?is)<table[^>]*>(.*?)</table>").unwrap());
static RE_TR: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"(?is)<tr[^>]*>(.*?)</tr>").unwrap());
static RE_TH: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"(?is)<th[^>]*>(.*?)</th>").unwrap());
static RE_TD: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"(?is)<td[^>]*>(.*?)</td>").unwrap());
static RE_JSON_P: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r#"(?s)<p\s+id="main"[^>]*>(.*?)</p>"#).unwrap());
#[allow(dead_code)]
static RE_TABLE_DATA_HL: LazyLock<regex::Regex> = LazyLock::new(|| {
    regex::Regex::new(
        r#"(?is)<table[^>]*class="[^"]*data_table_1\s+m_table\s+m_hl[^"]*"[^>]*>(.*?)</table>"#,
    )
    .unwrap()
});
#[allow(dead_code)]
static RE_TABLE_M_DATA_HL: LazyLock<regex::Regex> = LazyLock::new(|| {
    regex::Regex::new(
        r#"(?is)<table[^>]*class="[^"]*m_table\s+data_table_1\s+m_hl[^"]*"[^>]*>(.*?)</table>"#,
    )
    .unwrap()
});
#[allow(dead_code)]
static RE_TABLE_MAINTABLE: LazyLock<regex::Regex> = LazyLock::new(|| {
    regex::Regex::new(r#"(?is)<table[^>]*id="maintable"[^>]*>(.*?)</table>"#).unwrap()
});
#[allow(dead_code)]
static RE_TABLE_M_TABLE: LazyLock<regex::Regex> = LazyLock::new(|| {
    regex::Regex::new(r#"(?is)<table[^>]*class="[^"]*m_table[^"]*"[^>]*>(.*?)</table>"#).unwrap()
});
#[allow(dead_code)]
static RE_UL_MAIN_INTRO: LazyLock<regex::Regex> = LazyLock::new(|| {
    regex::Regex::new(r#"(?is)<ul[^>]*class="[^"]*main_intro_list[^"]*"[^>]*>(.*?)</ul>"#).unwrap()
});
#[allow(dead_code)]
static RE_LI: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"(?is)<li[^>]*>(.*?)</li>").unwrap());

// ---------------------------------------------------------------------------
// Shared THS headers
// ---------------------------------------------------------------------------

fn ths_headers() -> reqwest::header::HeaderMap {
    let mut headers = reqwest::header::HeaderMap::new();
    headers.insert(
        reqwest::header::USER_AGENT,
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
            .parse()
            .unwrap(),
    );
    headers
}

// ---------------------------------------------------------------------------
// Market code helper for THS new API
// ---------------------------------------------------------------------------

fn ths_market_code(stock_code: &str) -> i32 {
    let code = stock_code.trim();
    if code.starts_with("000")
        || code.starts_with("001")
        || code.starts_with("002")
        || code.starts_with("003")
        || code.starts_with("300")
    {
        return 33; // Shenzhen
    }
    if code.starts_with("600")
        || code.starts_with("601")
        || code.starts_with("603")
        || code.starts_with("605")
        || code.starts_with("688")
    {
        return 17; // Shanghai
    }
    if code.starts_with("920") {
        return 151; // Beijing
    }
    0
}

// ---------------------------------------------------------------------------
// Period mapping for THS new API
// ---------------------------------------------------------------------------

fn ths_period_code(indicator: &str) -> &str {
    match indicator {
        "按报告期" => "0",
        "一季度" => "1",
        "二季度" => "2",
        "三季度" => "3",
        _ => "4",
    }
}

// ---------------------------------------------------------------------------
// HTML table parsing (reused from sina module pattern)
// ---------------------------------------------------------------------------

fn strip_html_tags(s: &str) -> String {
    RE_HTML_TAG.replace_all(s, "").to_string()
}

fn parse_html_tables(html: &str) -> Vec<(Vec<String>, Vec<Vec<String>>)> {
    let mut tables = Vec::new();
    for table_cap in RE_TABLE.captures_iter(html) {
        let table_content = &table_cap[1];

        let mut rows = Vec::new();
        for row_cap in RE_TR.captures_iter(table_content) {
            let row_content = &row_cap[1];
            let ths: Vec<String> = RE_TH
                .captures_iter(row_content)
                .map(|c| strip_html_tags(&c[1]).trim().to_string())
                .collect();
            if !ths.is_empty() {
                rows.push(ths);
                continue;
            }
            let tds: Vec<String> = RE_TD
                .captures_iter(row_content)
                .map(|c| strip_html_tags(&c[1]).trim().to_string())
                .collect();
            if !tds.is_empty() {
                rows.push(tds);
            }
        }

        if rows.is_empty() {
            continue;
        }

        let headers = rows[0].clone();
        let data_rows = rows[1..].to_vec();
        tables.push((headers, data_rows));
    }
    tables
}

fn table_to_records(
    headers: &[String],
    rows: &[Vec<String>],
) -> Vec<HashMap<String, serde_json::Value>> {
    rows.iter()
        .filter(|row| !row.is_empty())
        .map(|row| {
            let mut map = HashMap::new();
            for (i, header) in headers.iter().enumerate() {
                let val = row.get(i).cloned().unwrap_or_default();
                map.insert(header.clone(), serde_json::Value::String(val));
            }
            map
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Implementation
// ---------------------------------------------------------------------------

impl AkShareClient {
    // -----------------------------------------------------------------------
    // THS old-style financial APIs (JSON embedded in HTML)
    // -----------------------------------------------------------------------

    /// THS financial abstract (主要指标) - old API.
    ///
    /// `symbol` is the stock code, e.g. "000063".
    /// `indicator` is one of "按报告期", "按年度", "按单季度".
    pub async fn stock_financial_abstract_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = format!("https://basic.10jqka.com.cn/new/{symbol}/finance.html");
        let html = self
            .get(&url)
            .headers(ths_headers())
            .send()
            .await?
            .text()
            .await?;

        // Extract JSON from <p id="main">...</p>
        let json_str = RE_JSON_P
            .captures(&html)
            .map(|c| c[1].trim().to_string())
            .ok_or_else(|| Error::upstream("THS finance page: main JSON not found"))?;

        let data_json: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| Error::decode(format!("THS finance JSON parse error: {e}")))?;

        Ok(Self::parse_ths_finance_json(
            &data_json, indicator, "report",
        ))
    }

    /// THS balance sheet (资产负债表) - old API.
    pub async fn stock_financial_debt_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = format!("https://basic.10jqka.com.cn/api/stock/finance/{symbol}_debt.json");
        self.fetch_ths_json_table(&url, indicator, false).await
    }

    /// THS income statement (利润表) - old API.
    pub async fn stock_financial_benefit_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = format!("https://basic.10jqka.com.cn/api/stock/finance/{symbol}_benefit.json");
        self.fetch_ths_json_table(&url, indicator, true).await
    }

    /// THS cash flow statement (现金流量表) - old API.
    pub async fn stock_financial_cash_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = format!("https://basic.10jqka.com.cn/api/stock/finance/{symbol}_cash.json");
        self.fetch_ths_json_table(&url, indicator, true).await
    }

    async fn fetch_ths_json_table(
        &self,
        url: &str,
        indicator: &str,
        has_simple: bool,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let resp = self
            .get(url)
            .headers(ths_headers())
            .send()
            .await?
            .error_for_status()?;

        let outer: serde_json::Value = resp.json().await?;
        let flash_data_str = outer
            .get("flashData")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::upstream("THS response missing flashData"))?;

        // flashData is a JSON string that needs to be parsed again
        let inner_str = if flash_data_str.starts_with('"') {
            // Double-encoded JSON string
            serde_json::from_str::<String>(flash_data_str)
                .map_err(|e| Error::decode(format!("THS flashData decode error: {e}")))?
        } else {
            flash_data_str.to_string()
        };

        let data_json: serde_json::Value = serde_json::from_str(&inner_str)
            .map_err(|e| Error::decode(format!("THS flashData JSON parse error: {e}")))?;

        let default_key = if has_simple { "simple" } else { "report" };
        Ok(Self::parse_ths_finance_json(
            &data_json,
            indicator,
            default_key,
        ))
    }

    fn parse_ths_finance_json(
        data_json: &serde_json::Value,
        indicator: &str,
        default_key: &str,
    ) -> Vec<HashMap<String, serde_json::Value>> {
        // Extract title (row labels)
        let titles: Vec<String> = data_json
            .get("title")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .map(|item| {
                        if let Some(s) = item.as_str() {
                            s.to_string()
                        } else if let Some(arr) = item.as_array() {
                            arr.first()
                                .and_then(|v| v.as_str())
                                .unwrap_or("")
                                .to_string()
                        } else {
                            String::new()
                        }
                    })
                    .collect()
            })
            .unwrap_or_default();

        // Select the data key based on indicator
        let data_key = match indicator {
            "按报告期" => "report",
            "按单季度" => {
                if data_json.get("simple").is_some() {
                    "simple"
                } else {
                    default_key
                }
            }
            "按年度" => "year",
            _ => default_key,
        };

        let table_data = data_json
            .get(data_key)
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        if table_data.is_empty() {
            return vec![];
        }

        // First row is column headers (report dates)
        let column_headers: Vec<String> = table_data
            .first()
            .and_then(|row| row.as_array())
            .map(|arr| {
                arr.iter()
                    .map(|v| v.as_str().unwrap_or("").to_string())
                    .collect()
            })
            .unwrap_or_default();

        // Data rows start from index 1
        let mut all_records = Vec::new();
        for (row_idx, row_val) in table_data.iter().enumerate().skip(1) {
            let cells: Vec<String> = row_val
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .map(|v| v.as_str().unwrap_or("").to_string())
                        .collect()
                })
                .unwrap_or_default();

            let row_label = titles.get(row_idx).cloned().unwrap_or_default();

            // Each column (after the first) is a report period
            for (col_idx, col_header) in column_headers.iter().enumerate().skip(1) {
                let mut record = HashMap::new();
                record.insert(
                    "报告期".to_string(),
                    serde_json::Value::String(col_header.clone()),
                );
                record.insert(
                    "指标".to_string(),
                    serde_json::Value::String(row_label.clone()),
                );
                if let Some(val) = cells.get(col_idx) {
                    record.insert("".to_string(), serde_json::Value::String(val.clone()));
                }
                all_records.push(record);
            }
        }

        all_records
    }

    // -----------------------------------------------------------------------
    // THS new-style financial APIs
    // -----------------------------------------------------------------------

    /// THS new financial abstract (重要指标).
    ///
    /// `symbol` is the stock code, e.g. "000063".
    /// `indicator` is one of "按报告期", "一季度", "二季度", "三季度", "四季度", "按年度".
    pub async fn stock_financial_abstract_new_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        self.fetch_ths_new_api(symbol, "client_stock_importance", indicator)
            .await
    }

    /// THS new balance sheet (资产负债表).
    pub async fn stock_financial_debt_new_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let ind = if indicator == "按报告期" {
            "按报告期"
        } else {
            "按年度"
        };
        self.fetch_ths_new_api(symbol, "client_stock_debt", ind)
            .await
    }

    /// THS new income statement (利润表).
    pub async fn stock_financial_benefit_new_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        self.fetch_ths_new_api(symbol, "client_stock_benefit", indicator)
            .await
    }

    /// THS new cash flow statement (现金流量表).
    pub async fn stock_financial_cash_new_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        self.fetch_ths_new_api(symbol, "client_stock_cash", indicator)
            .await
    }

    async fn fetch_ths_new_api(
        &self,
        symbol: &str,
        api_id: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = "https://basic.10jqka.com.cn/basicapi/finance/index/v1/app_data/";
        let market = ths_market_code(symbol).to_string();
        let period = ths_period_code(indicator);

        let resp = self
            .get(url)
            .headers(ths_headers())
            .query(&[
                ("code", symbol),
                ("id", api_id),
                ("market", market.as_str()),
                ("type", "stock"),
                ("page", "1"),
                ("size", "50"),
                ("period", period),
            ])
            .send()
            .await?
            .error_for_status()?;

        let payload: serde_json::Value = resp.json().await?;
        let financial_data = payload
            .pointer("/data/data")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        let mut all_records = Vec::new();
        for report in &financial_data {
            let report_date = report.get("date").and_then(|v| v.as_str()).unwrap_or("");
            let report_name = report
                .get("report_name")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let report_period = report.get("report").and_then(|v| v.as_str()).unwrap_or("");
            let quarter_name = report
                .get("quarter_name")
                .and_then(|v| v.as_str())
                .unwrap_or("");

            let Some(serde_json::Value::Object(index_list)) = report.get("index_list") else {
                continue;
            };

            for (metric_name, metric_values) in index_list {
                let mut record = HashMap::new();
                record.insert(
                    "report_date".to_string(),
                    serde_json::Value::String(report_date.to_string()),
                );
                record.insert(
                    "report_name".to_string(),
                    serde_json::Value::String(report_name.to_string()),
                );
                record.insert(
                    "report_period".to_string(),
                    serde_json::Value::String(report_period.to_string()),
                );
                record.insert(
                    "quarter_name".to_string(),
                    serde_json::Value::String(quarter_name.to_string()),
                );
                record.insert(
                    "metric_name".to_string(),
                    serde_json::Value::String(metric_name.clone()),
                );

                if let serde_json::Value::Object(vals) = metric_values {
                    for (field, value) in vals {
                        record.insert(field.clone(), value.clone());
                    }
                } else {
                    record.insert("value".to_string(), metric_values.clone());
                }

                all_records.push(record);
            }
        }

        Ok(all_records)
    }

    // -----------------------------------------------------------------------
    // Management / shareholder changes
    // -----------------------------------------------------------------------

    /// THS management shareholding changes (高管持股变动).
    pub async fn stock_management_change_ths(
        &self,
        symbol: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = format!("https://basic.10jqka.com.cn/new/{symbol}/event.html");
        let html = self
            .get(&url)
            .headers(ths_headers())
            .send()
            .await?
            .text()
            .await?;

        // Parse the management change table
        // Look for table with class "data_table_1 m_table m_hl"
        let table_content = match RE_TABLE_DATA_HL.captures(&html) {
            Some(cap) => cap[1].to_string(),
            None => return Ok(vec![]),
        };

        let tables = parse_html_tables(&format!("<table>{table_content}</table>"));
        if tables.is_empty() {
            return Ok(vec![]);
        }

        let (headers, rows) = &tables[0];
        Ok(table_to_records(headers, rows))
    }

    /// THS shareholder shareholding changes (股东持股变动).
    pub async fn stock_shareholder_change_ths(
        &self,
        symbol: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = format!("https://basic.10jqka.com.cn/new/{symbol}/event.html");
        let html = self
            .get(&url)
            .headers(ths_headers())
            .send()
            .await?
            .text()
            .await?;

        // Look for table with class "m_table data_table_1 m_hl"
        let table_content = match RE_TABLE_M_DATA_HL.captures(&html) {
            Some(cap) => cap[1].to_string(),
            None => return Ok(vec![]),
        };

        let tables = parse_html_tables(&format!("<table>{table_content}</table>"));
        if tables.is_empty() {
            return Ok(vec![]);
        }

        let (headers, rows) = &tables[0];
        Ok(table_to_records(headers, rows))
    }

    // -----------------------------------------------------------------------
    // THS IPO data
    // -----------------------------------------------------------------------

    /// THS IPO subscription and allotment data (新股申购与中签).
    ///
    /// `market` is one of: "全部A股", "沪市主板", "深市主板", "创业板", "科创板", "京市主板".
    pub async fn stock_ipo_ths(
        &self,
        market: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let market_map: HashMap<&str, &str> = [
            ("全部A股", "all"),
            ("沪市主板", "hszb"),
            ("深市主板", "sszb"),
            ("创业板", "cyb"),
            ("科创板", "kcbsg"),
            ("京市主板", "bjzb"),
        ]
        .into_iter()
        .collect();

        let path = market_map
            .get(market)
            .copied()
            .ok_or_else(|| Error::invalid_input(format!("unsupported market: {market}")))?;

        let url = format!("https://data.10jqka.com.cn/ipo/xgsgyzq/{path}/");
        let html = self
            .get(&url)
            .headers(ths_headers())
            .send()
            .await?
            .error_for_status()?
            .text()
            .await?;

        // Parse the main table
        let table_content = RE_TABLE_MAINTABLE
            .captures(&html)
            .or_else(|| RE_TABLE_M_TABLE.captures(&html))
            .map(|c| c[1].to_string());

        let Some(content) = table_content else {
            return Ok(vec![]);
        };

        let tables = parse_html_tables(&format!("<table>{content}</table>"));
        if tables.is_empty() {
            return Ok(vec![]);
        }

        let (headers, rows) = &tables[0];
        Ok(table_to_records(headers, rows))
    }

    /// THS HK IPO subscription and allotment data (港股新股申购与中签).
    pub async fn stock_ipo_hk_ths(&self) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = "https://data.10jqka.com.cn/ipo/xgsgyzq/hkstock/";
        let html = self
            .get(url)
            .headers(ths_headers())
            .send()
            .await?
            .error_for_status()?
            .text()
            .await?;

        let table_content = RE_TABLE_MAINTABLE
            .captures(&html)
            .or_else(|| RE_TABLE_M_TABLE.captures(&html))
            .map(|c| c[1].to_string());

        let Some(content) = table_content else {
            return Ok(vec![]);
        };

        let tables = parse_html_tables(&format!("<table>{content}</table>"));
        if tables.is_empty() {
            return Ok(vec![]);
        }

        let (headers, rows) = &tables[0];
        Ok(table_to_records(headers, rows))
    }

    // -----------------------------------------------------------------------
    // THS profit forecast
    // -----------------------------------------------------------------------

    /// THS profit forecast (盈利预测).
    ///
    /// `symbol` is the stock code, e.g. "600519".
    /// `indicator` is one of: "预测年报每股收益", "预测年报净利润",
    /// "业绩预测详表-机构", "业绩预测详表-详细指标预测".
    pub async fn stock_profit_forecast_ths(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let url = format!("https://basic.10jqka.com.cn/new/{symbol}/worth.html");
        let resp = self.get(&url).headers(ths_headers()).send().await?;

        let bytes = resp.bytes().await?;
        let html = String::from_utf8_lossy(&bytes).to_string();

        let tables = parse_html_tables(&html);

        // Check if there's a "no forecast" message
        if html.contains("本年度暂无机构做出业绩预测") {
            match indicator {
                "业绩预测详表-机构" => {
                    if tables.is_empty() {
                        return Ok(vec![]);
                    }
                    let (headers, rows) = &tables[0];
                    return Ok(table_to_records(headers, rows));
                }
                "业绩预测详表-详细指标预测" => {
                    if tables.len() < 2 {
                        return Ok(vec![]);
                    }
                    let (headers, rows) = &tables[1];
                    return Ok(table_to_records(headers, rows));
                }
                _ => return Ok(vec![]),
            }
        }

        let table_idx = match indicator {
            "预测年报每股收益" => 0,
            "预测年报净利润" => 1,
            "业绩预测详表-机构" => 2,
            "业绩预测详表-详细指标预测" => 3,
            _ => {
                return Err(Error::invalid_input(format!(
                    "unsupported indicator: {indicator}"
                )));
            }
        };

        if table_idx >= tables.len() {
            return Ok(vec![]);
        }

        let (headers, rows) = &tables[table_idx];
        Ok(table_to_records(headers, rows))
    }

    // -----------------------------------------------------------------------
    // THS main business introduction
    // -----------------------------------------------------------------------

    /// THS main business introduction (主营介绍).
    ///
    /// `symbol` is the stock code, e.g. "000066".
    pub async fn stock_zyjs_ths(&self, symbol: &str) -> Result<HashMap<String, serde_json::Value>> {
        let url = format!("https://basic.10jqka.com.cn/new/{symbol}/operate.html");
        let resp = self.get(&url).headers(ths_headers()).send().await?;

        let bytes = resp.bytes().await?;
        let html = String::from_utf8_lossy(&bytes).to_string();

        // Extract the main_intro_list items
        let mut result = HashMap::new();
        result.insert(
            "股票代码".to_string(),
            serde_json::Value::String(symbol.to_string()),
        );

        if let Some(list_cap) = RE_UL_MAIN_INTRO.captures(&html) {
            let list_content = &list_cap[1];
            for li_cap in RE_LI.captures_iter(list_content) {
                let text = strip_html_tags(&li_cap[1])
                    .replace(['\t', '\n'], "")
                    .replace("  ", "")
                    .trim()
                    .to_string();

                if let Some((key, value)) = text.split_once('') {
                    result.insert(
                        key.trim().to_string(),
                        serde_json::Value::String(value.trim().to_string()),
                    );
                } else if let Some((key, value)) = text.split_once(':') {
                    result.insert(
                        key.trim().to_string(),
                        serde_json::Value::String(value.trim().to_string()),
                    );
                }
            }
        }

        Ok(result)
    }

    // -----------------------------------------------------------------------
    // HK profit forecast from ET Net
    // -----------------------------------------------------------------------

    /// HK stock profit forecast from ET Net (经济通).
    ///
    /// `symbol` is the HK stock code, e.g. "09999".
    /// `indicator` is one of: "评级总览", "去年度业绩表现", "综合盈利预测", "盈利预测概览".
    pub async fn stock_hk_profit_forecast_et(
        &self,
        symbol: &str,
        indicator: &str,
    ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
        let code = symbol.trim_start_matches('0');
        let code = if code.is_empty() { "0" } else { code };

        let url = "https://www.etnet.com.hk/www/sc/stocks/realtime/quote_profit.php";
        let html = self
            .get(url)
            .query(&[("code", code)])
            .send()
            .await?
            .text()
            .await?;

        let tables = parse_html_tables(&html);

        match indicator {
            "评级总览" => {
                if tables.is_empty() {
                    return Ok(vec![]);
                }
                let (headers, rows) = &tables[0];
                Ok(table_to_records(headers, rows))
            }
            "去年度业绩表现" => {
                if tables.len() < 3 {
                    return Ok(vec![]);
                }
                let (headers, rows) = &tables[2];
                Ok(table_to_records(headers, rows))
            }
            "综合盈利预测" => {
                if tables.len() < 4 {
                    return Ok(vec![]);
                }
                let (headers, rows) = &tables[3];
                Ok(table_to_records(headers, rows))
            }
            "盈利预测概览" => {
                if tables.len() < 5 {
                    return Ok(vec![]);
                }
                let (headers, rows) = &tables[4];
                Ok(table_to_records(headers, rows))
            }
            _ => Err(Error::invalid_input(format!(
                "unsupported indicator: {indicator}"
            ))),
        }
    }
}