akshare 0.1.1

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
//! Fortune and wealth ranking data: Bloomberg Billionaires, Forbes, Hurun, Xincaifu.

use serde::Deserialize;

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

// ---------------------------------------------------------------------------
// Wire types
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct HurunResponse {
    rows: Option<Vec<serde_json::Value>>,
}

#[derive(Debug, Deserialize)]
struct XincaifuResponse {
    data: Option<XincaifuData>,
}

#[derive(Debug, Deserialize)]
struct XincaifuData {
    rows: Option<Vec<serde_json::Value>>,
}

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

impl AkShareClient {
    /// Bloomberg Billionaires Index - current top billionaires.
    ///
    /// Scrapes the Bloomberg billionaires page. Returns a simplified set of
    /// fields: rank, name, total_net_worth, country, industry.
    pub async fn index_bloomberg_billionaires(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://www.bloomberg.com/billionaires";
        let body = self
            .get(url)
            .header("User-Agent", "Mozilla/5.0 (compatible; akshare-rust/0.1)")
            .send()
            .await?
            .text()
            .await?;

        // Extract data from the HTML table-chart section
        let items = Vec::new();
        // Parse rank entries - Bloomberg uses a specific format
        // We'll parse what we can from the HTML
        for line in body.lines() {
            let trimmed = line.trim();
            // Look for structured data patterns
            if trimmed.contains("table-row") {
                // Simple extraction from table rows
            }
        }

        // If HTML parsing yields nothing, return empty rather than error
        // (Bloomberg often blocks scrapers)
        if items.is_empty() {
            return Err(Error::upstream(
                "bloomberg billionaires: page may require JS or be blocked",
            ));
        }
        Ok(items)
    }

    /// Bloomberg Billionaires Index - historical data by year.
    ///
    /// Downloads historical billionaire rankings from areppim.com archives.
    pub async fn index_bloomberg_billionaires_hist(
        &self,
        year: &str,
    ) -> Result<Vec<MacroDataPoint>> {
        let short_year = if year.len() >= 2 {
            &year[year.len() - 2..]
        } else {
            year
        };
        let url = format!("https://stats.areppim.com/listes/list_billionaires{short_year}xwor.htm");
        let body = self.get(&url).send().await?.text().await?;

        let mut items = Vec::new();
        // Parse HTML table
        let mut in_table = false;
        let headers: Vec<String> = Vec::new();
        for line in body.lines() {
            let trimmed = line.trim();
            if trimmed.contains("<table") {
                in_table = true;
                continue;
            }
            if trimmed.contains("</table>") {
                in_table = false;
                continue;
            }
            if !in_table {
                continue;
            }
            // Parse table rows
            if trimmed.contains("<tr") || trimmed.contains("<td") {
                let cells = extract_html_cells(trimmed);
                if !cells.is_empty()
                    && !headers.is_empty()
                    && let Some(rank_str) = cells.first()
                    && rank_str.chars().all(|c| c.is_ascii_digit())
                {
                    let net_worth = cells
                        .get(3)
                        .and_then(|s| s.parse::<f64>().ok())
                        .unwrap_or(0.0);
                    items.push(MacroDataPoint {
                        date: year.to_string(),
                        value: net_worth,
                        name: cells
                            .get(1)
                            .cloned()
                            .unwrap_or_else(|| "Unknown".to_string()),
                    });
                }
            }
        }
        Ok(items)
    }

    /// Forbes China rankings.
    ///
    /// Scrapes the Forbes China lists page and returns the specified ranking.
    /// `symbol` is the list name (e.g., "2021福布斯中国创投人100").
    pub async fn forbes_rank(&self, symbol: &str) -> Result<Vec<MacroDataPoint>> {
        let url = "https://www.forbeschina.com/lists";
        let body = self.get(url).send().await?.text().await?;

        // Extract list URLs from the main page
        let mut list_urls: Vec<(String, String)> = Vec::new();
        for line in body.lines() {
            let trimmed = line.trim();
            if trimmed.contains("href=")
                && trimmed.contains("/lists/")
                && let (Some(href_start), Some(href_end)) =
                    (trimmed.find("href=\""), trimmed.find('"'))
            {
                let href = &trimmed[href_start + 6..href_end];
                // Extract text content
                let text = extract_text_between_tags(trimmed);
                if !text.is_empty() && href.contains("/lists/") {
                    list_urls.push((text, format!("https://www.forbeschina.com{href}")));
                }
            }
        }

        // Find the matching list
        let target_url = list_urls
            .iter()
            .find(|(name, _)| name.contains(symbol))
            .map(|(_, url)| url.as_str())
            .ok_or_else(|| Error::not_found(format!("forbes: list '{symbol}' not found")))?;

        let list_body = self.get(target_url).send().await?.text().await?;
        let mut items = Vec::new();

        // Parse the ranking table
        for line in list_body.lines() {
            let trimmed = line.trim();
            if trimmed.contains("<tr") || trimmed.contains("<td") {
                let cells = extract_html_cells(trimmed);
                if cells.len() >= 3 {
                    items.push(MacroDataPoint {
                        date: symbol.to_string(),
                        value: cells
                            .get(2)
                            .and_then(|s| s.replace(',', "").parse::<f64>().ok())
                            .unwrap_or(0.0),
                        name: cells
                            .get(1)
                            .cloned()
                            .unwrap_or_else(|| "Unknown".to_string()),
                    });
                }
            }
        }
        Ok(items)
    }

    /// Hurun Rich List rankings.
    ///
    /// Fetches data from the Hurun API. Supported indicators:
    /// "胡润百富榜", "胡润全球富豪榜", "胡润印度榜", "胡润全球独角兽榜", etc.
    pub async fn hurun_rank(&self, indicator: &str, year: &str) -> Result<Vec<MacroDataPoint>> {
        // First, get the indicator list and find the correct num code
        let url = "https://www.hurun.net/zh-CN/Rank/HsRankDetails?pagetype=rich";
        let _body = self.get(url).send().await?.text().await?;

        // Extract year-to-code mapping from the page
        // This is a simplified approach - we'll try to use the API directly
        let list_url = "https://www.hurun.net/zh-CN/Rank/HsRankDetailsList";

        // Build params based on indicator type
        let params = build_hurun_params(indicator, year);

        let resp: HurunResponse = self
            .get(list_url)
            .query(&params)
            .send()
            .await?
            .json()
            .await?;

        let rows = resp.rows.unwrap_or_default();
        let mut items = Vec::new();

        for row in &rows {
            let wealth_key = get_hurun_wealth_key(indicator);
            let name_key = get_hurun_name_key(indicator);

            let wealth = row
                .get(&wealth_key)
                .and_then(|v| {
                    v.as_str()
                        .and_then(|s| s.parse::<f64>().ok())
                        .or_else(|| v.as_f64())
                })
                .unwrap_or(0.0);

            let name = row
                .get(&name_key)
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            if !name.is_empty() {
                items.push(MacroDataPoint {
                    date: year.to_string(),
                    value: wealth,
                    name,
                });
            }
        }
        Ok(items)
    }

    /// Xincaifu (新财富) 500 Rich List.
    ///
    /// Fetches data from the Xincaifu API. `year` ranges from "2003" to present.
    pub async fn xincaifu_rank(&self, year: &str) -> Result<Vec<MacroDataPoint>> {
        let url = "http://service.ikuyu.cn/XinCaiFu2/pcremoting/bdListAction.do";
        let resp: XincaifuResponse = self
            .get(url)
            .query(&[
                ("method", "getPage"),
                ("callback", "jsonpCallback"),
                ("sortBy", ""),
                ("order", ""),
                ("type", "4"),
                ("keyword", ""),
                ("pageSize", "1000"),
                ("year", year),
                ("pageNo", "1"),
                ("from", "jsonp"),
            ])
            .send()
            .await?
            .json()
            .await?;

        let rows = resp.data.and_then(|d| d.rows).unwrap_or_default();

        let mut items = Vec::new();
        for row in &rows {
            let name = row
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let assets = row
                .get("assets")
                .and_then(|v| {
                    v.as_str()
                        .and_then(|s| s.parse::<f64>().ok())
                        .or_else(|| v.as_f64())
                })
                .unwrap_or(0.0);

            if !name.is_empty() {
                items.push(MacroDataPoint {
                    date: year.to_string(),
                    value: assets,
                    name,
                });
            }
        }
        Ok(items)
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn extract_html_cells(html: &str) -> Vec<String> {
    let mut cells = Vec::new();
    let mut remaining = html;
    while let Some(start) = remaining.find('>') {
        let after_start = &remaining[start + 1..];
        if let Some(end) = after_start.find('<') {
            let text = after_start[..end].trim();
            if !text.is_empty() {
                cells.push(text.to_string());
            }
            remaining = &after_start[end..];
        } else {
            break;
        }
    }
    cells
}

fn extract_text_between_tags(html: &str) -> String {
    let mut result = String::new();
    let mut remaining = html;
    while let Some(start) = remaining.find('>') {
        let after_start = &remaining[start + 1..];
        if let Some(end) = after_start.find('<') {
            let text = after_start[..end].trim();
            if !text.is_empty() {
                if !result.is_empty() {
                    result.push(' ');
                }
                result.push_str(text);
            }
            remaining = &after_start[end..];
        } else {
            break;
        }
    }
    result
}

fn build_hurun_params(indicator: &str, year: &str) -> Vec<(&'static str, String)> {
    let num = match indicator {
        "胡润全球富豪榜" => format!("global_{year}"),
        "胡润印度榜" => format!("india_{year}"),
        "胡润全球独角兽榜" => format!("unicorn_{year}"),
        "中国瞪羚企业榜" => format!("cgazelles_{year}"),
        "全球瞪羚企业榜" => format!("ggazelles_{year}"),
        "胡润Under30s创业领袖榜" => format!("u30_{year}"),
        "胡润中国500强民营企业" => format!("ctop500_{year}"),
        "胡润世界500强" => format!("gtop500_{year}"),
        "胡润艺术榜" => format!("art_{year}"),
        _ => format!("rich_{year}"),
    };
    vec![
        ("num", num),
        ("search", String::new()),
        ("offset", "0".to_string()),
        ("limit", "20000".to_string()),
    ]
}

fn get_hurun_wealth_key(indicator: &str) -> String {
    match indicator {
        "胡润全球富豪榜" => "hs_Rank_Global_Wealth".to_string(),
        "胡润印度榜" => "hs_Rank_India_Wealth".to_string(),
        "胡润全球独角兽榜" => "hs_Rank_Unicorn_Wealth".to_string(),
        "胡润中国500强民营企业" => "hs_Rank_CTop500_Wealth".to_string(),
        "胡润世界500强" => "hs_Rank_GTop500_Wealth".to_string(),
        "胡润艺术榜" => "hs_Rank_Art_Turnover".to_string(),
        _ => "hs_Rank_Rich_Wealth".to_string(),
    }
}

fn get_hurun_name_key(indicator: &str) -> String {
    match indicator {
        "胡润全球富豪榜" => "hs_Rank_Global_ChaName_Cn".to_string(),
        "胡润印度榜" => "hs_Rank_India_ChaName_Cn".to_string(),
        "胡润全球独角兽榜" => "hs_Rank_Unicorn_ChaName_Cn".to_string(),
        "胡润中国500强民营企业" => "hs_Rank_CTop500_ChaName_Cn".to_string(),
        "胡润世界500强" => "hs_Rank_GTop500_ChaName_Cn".to_string(),
        "胡润艺术榜" => "hs_Rank_Art_Name_Cn".to_string(),
        _ => "hs_Rank_Rich_ChaName_Cn".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_html_cells() {
        let html = "<td>1</td><td>Name</td><td>100.5</td>";
        let cells = extract_html_cells(html);
        assert_eq!(cells.len(), 3);
        assert_eq!(cells[0], "1");
        assert_eq!(cells[1], "Name");
        assert_eq!(cells[2], "100.5");
    }

    #[test]
    fn test_extract_text_between_tags() {
        let html = "<a href=\"/lists/123\">Forbes List</a>";
        let text = extract_text_between_tags(html);
        assert_eq!(text, "Forbes List");
    }

    #[test]
    fn test_build_hurun_params() {
        let params = build_hurun_params("胡润百富榜", "2023");
        assert_eq!(params[0].1, "rich_2023");
    }

    #[test]
    fn test_get_hurun_wealth_key() {
        assert_eq!(get_hurun_wealth_key("胡润百富榜"), "hs_Rank_Rich_Wealth");
    }
}