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
//! Repo rate data from China Money (中国外汇交易中心).
use serde::Deserialize;
use crate::client::AkShareClient;
use crate::error::Result;
use crate::types::MacroDataPoint;
// ---------------------------------------------------------------------------
// Wire types
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
struct FrrResponse {
records: Option<Vec<serde_json::Value>>,
}
// ---------------------------------------------------------------------------
// Implementation
// ---------------------------------------------------------------------------
impl AkShareClient {
/// China Money - repo fixing rate query.
///
/// Returns the latest repo fixing rates (FR001, FR007, FR014) from
/// China Foreign Exchange Trade System.
///
/// `symbol`: "回购定盘利率" or "银银间回购定盘利率"
pub async fn repo_rate_query(&self, symbol: &str) -> Result<Vec<MacroDataPoint>> {
let (url, col_names) = if symbol == "银银间回购定盘利率" {
(
"https://www.chinamoney.com.cn/r/cms/www/chinamoney/data/currency/fdr-chrt.csv",
vec!["FDR001", "FDR007", "FDR014"],
)
} else {
(
"https://www.chinamoney.com.cn/r/cms/www/chinamoney/data/currency/frr-chrt.csv",
vec!["FR001", "FR007", "FR014"],
)
};
let body = self.get(url).send().await?.text().await?;
let mut items = Vec::new();
for line in body.lines() {
let fields: Vec<&str> = line.split(',').filter(|s| !s.trim().is_empty()).collect();
if fields.len() < 4 {
continue;
}
let date = fields[0].trim().to_string();
if date.is_empty() || !date.contains('-') {
continue;
}
for (i, col_name) in col_names.iter().enumerate() {
if let Some(val) = fields.get(i + 1).and_then(|s| s.trim().parse::<f64>().ok()) {
items.push(MacroDataPoint {
date: date.clone(),
value: val,
name: col_name.to_string(),
});
}
}
}
Ok(items)
}
/// China Money - historical repo fixing rates.
///
/// Returns historical FR001/FR007/FR014/FDR001/FDR007/FDR014 rates
/// for the given date range.
///
/// `start_date` and `end_date` in "YYYYMMDD" format. Must be within
/// one month of each other.
pub async fn repo_rate_hist(
&self,
start_date: &str,
end_date: &str,
) -> Result<Vec<MacroDataPoint>> {
let formatted_start = format!(
"{}-{}-{}",
&start_date[..4],
&start_date[4..6],
&start_date[6..8]
);
let formatted_end = format!("{}-{}-{}", &end_date[..4], &end_date[4..6], &end_date[6..8]);
let url = "https://www.chinamoney.com.cn/ags/ms/cm-u-bk-currency/FrrHis";
let resp: FrrResponse = self
.post(url)
.query(&[
("lang", "CN"),
("startDate", &formatted_start),
("endDate", &formatted_end),
])
.header("User-Agent", "Mozilla/5.0 (compatible; akshare-rust/0.1)")
.send()
.await?
.json()
.await?;
let records = resp.records.unwrap_or_default();
let mut items = Vec::new();
for record in &records {
if let Some(fr_map) = record.get("frValueMap") {
let date = fr_map
.get("date")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
for key in &["FR001", "FR007", "FR014", "FDR001", "FDR007", "FDR014"] {
if let Some(val) = fr_map.get(*key).and_then(serde_json::Value::as_f64) {
items.push(MacroDataPoint {
date: date.clone(),
value: val,
name: key.to_string(),
});
}
}
}
}
items.sort_by(|a, b| a.date.cmp(&b.date));
Ok(items)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_frr_response_structure() {
let json = r#"{
"records": [
{
"frValueMap": {
"date": "2024-01-02",
"FR001": 1.5,
"FR007": 1.8,
"FR014": 2.0,
"FDR001": 1.6,
"FDR007": 1.9,
"FDR014": 2.1
}
}
]
}"#;
let resp: super::FrrResponse = serde_json::from_str(json).unwrap();
assert_eq!(resp.records.as_ref().unwrap().len(), 1);
}
}