qmt-parser 0.2.1

Rust parser for MiniQMT/QMT local market data, finance files, and dividend metadata.
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
//! 基于 QMT `datadir` 根目录的自动发现入口。
//!
//! 这个模块把“文件路径拼装/发现”和“实际解析”拆开:
//!
//! - [`QmtDataDir`] 负责从 datadir 发现 tick、分钟线、日线、财务、分红和 metadata 文件
//! - 具体二进制解析仍委托给现有模块

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use chrono::NaiveDate;

use crate::day::{
    DailyKlineData, parse_daily_file_to_structs, parse_daily_to_structs,
    parse_daily_to_structs_in_range,
};
use crate::dividend::DividendDb;
use crate::error::DataDirError;
use crate::finance::{FileType, FinanceReader, FinanceRecord};
use crate::metadata::{
    load_holidays_from_root, load_industry_from_root, load_sector_names_from_root,
    load_sector_weight_index_from_root, load_sector_weight_members_from_root,
    load_sectorlist_from_root,
};
use crate::min::{MinKlineData, parse_min_to_structs};
use crate::tick::{TickData, parse_ticks_to_structs};

#[cfg(feature = "polars")]
use crate::day::{
    parse_daily_file_to_dataframe, parse_daily_to_dataframe, parse_daily_to_dataframe_in_range,
};
#[cfg(feature = "polars")]
use crate::min::parse_min_to_dataframe;
#[cfg(feature = "polars")]
use crate::tick::parse_ticks_to_dataframe;
#[cfg(feature = "polars")]
use polars::prelude::DataFrame;

/// 交易市场枚举。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Market {
    /// 上海市场。
    Sh,
    /// 深圳市场。
    Sz,
    /// 北京市场。
    Bj,
}

impl Market {
    /// 返回 QMT datadir 使用的市场目录名。
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Sh => "SH",
            Self::Sz => "SZ",
            Self::Bj => "BJ",
        }
    }
}

impl TryFrom<&str> for Market {
    type Error = DataDirError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let normalized = value.trim().to_ascii_uppercase();
        match normalized.as_str() {
            "SH" => Ok(Self::Sh),
            "SZ" => Ok(Self::Sz),
            "BJ" => Ok(Self::Bj),
            _ => Err(DataDirError::InvalidInput(format!(
                "unknown market: {value}"
            ))),
        }
    }
}

/// 解析证券代码字符串,支持 `SZ000001` 和 `000001.SZ` 格式。
pub fn parse_security_code(value: &str) -> Result<(Market, String), DataDirError> {
    let raw = value.trim();
    validate_non_empty("security_code", raw)?;

    if let Some((symbol, market)) = raw.rsplit_once('.') {
        validate_symbol(symbol)?;
        return Ok((Market::try_from(market)?, symbol.to_string()));
    }

    if raw.len() <= 2 {
        return Err(DataDirError::InvalidInput(format!(
            "unsupported security code: {value}"
        )));
    }

    let (market, symbol) = raw.split_at(2);
    validate_symbol(symbol)?;
    Ok((Market::try_from(market)?, symbol.to_string()))
}

/// QMT datadir 根目录句柄。
#[derive(Debug, Clone)]
pub struct QmtDataDir {
    root: PathBuf,
}

impl QmtDataDir {
    /// 创建 datadir 根目录句柄。
    pub fn new(path: impl AsRef<Path>) -> Result<Self, DataDirError> {
        let root = path.as_ref().to_path_buf();
        if !root.is_dir() {
            return Err(DataDirError::InvalidRoot(root));
        }
        Ok(Self { root })
    }

    /// 返回 datadir 根目录。
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// 定位 tick 文件路径。
    pub fn tick_path(
        &self,
        market: Market,
        symbol: &str,
        date: &str,
    ) -> Result<PathBuf, DataDirError> {
        validate_symbol(symbol)?;
        validate_date(date)?;
        first_existing(
            "tick file",
            vec![
                self.root
                    .join(market.as_str())
                    .join("0")
                    .join(symbol)
                    .join(format!("{date}.dat")),
                self.root
                    .join(market.as_str())
                    .join("0")
                    .join(symbol)
                    .join(format!("{date}.DAT")),
            ],
        )
    }

    /// 定位 1 分钟线文件路径。
    pub fn min_path(&self, market: Market, symbol: &str) -> Result<PathBuf, DataDirError> {
        validate_symbol(symbol)?;
        first_existing(
            "minute file",
            vec![
                self.root
                    .join(market.as_str())
                    .join("60")
                    .join(format!("{symbol}.dat")),
                self.root
                    .join(market.as_str())
                    .join("60")
                    .join(format!("{symbol}.DAT")),
            ],
        )
    }

    /// 定位日线文件路径。
    pub fn day_path(&self, market: Market, symbol: &str) -> Result<PathBuf, DataDirError> {
        validate_symbol(symbol)?;
        first_existing(
            "daily file",
            vec![
                self.root
                    .join(market.as_str())
                    .join("86400")
                    .join(format!("{symbol}.DAT")),
                self.root
                    .join(market.as_str())
                    .join("86400")
                    .join(format!("{symbol}.dat")),
            ],
        )
    }

    /// 定位财务文件路径。
    pub fn finance_path(&self, symbol: &str, file_type: FileType) -> Result<PathBuf, DataDirError> {
        validate_symbol(symbol)?;
        let file_id = file_type as u16;
        let filename_upper = format!("{symbol}_{file_id}.DAT");
        let filename_lower = format!("{symbol}_{file_id}.dat");
        first_existing(
            "finance file",
            vec![
                self.root.join("financial").join(&filename_upper),
                self.root.join("financial").join(&filename_lower),
                self.root.join("finance").join(&filename_upper),
                self.root.join("finance").join(&filename_lower),
                self.root.join("Finance").join(&filename_upper),
                self.root.join("Finance").join(&filename_lower),
            ],
        )
    }

    /// 定位分红 LevelDB 目录。
    pub fn dividend_db_path(&self) -> Result<PathBuf, DataDirError> {
        first_existing("dividend db", vec![self.root.join("DividData")])
    }

    /// 从 datadir 发现并解析 tick 文件为结构体。
    pub fn parse_ticks_to_structs(
        &self,
        market: Market,
        symbol: &str,
        date: &str,
    ) -> Result<Vec<TickData>, DataDirError> {
        Ok(parse_ticks_to_structs(
            self.tick_path(market, symbol, date)?,
        )?)
    }

    /// 从 datadir 发现并解析 tick 文件为 `DataFrame`。
    #[cfg(feature = "polars")]
    pub fn parse_ticks_to_dataframe(
        &self,
        market: Market,
        symbol: &str,
        date: &str,
    ) -> Result<DataFrame, DataDirError> {
        Ok(parse_ticks_to_dataframe(
            self.tick_path(market, symbol, date)?,
        )?)
    }

    /// 从 datadir 发现并解析 1 分钟线文件为结构体。
    pub fn parse_min_to_structs(
        &self,
        market: Market,
        symbol: &str,
    ) -> Result<Vec<MinKlineData>, DataDirError> {
        Ok(parse_min_to_structs(self.min_path(market, symbol)?)?)
    }

    /// 从 datadir 发现并解析 1 分钟线文件为 `DataFrame`。
    #[cfg(feature = "polars")]
    pub fn parse_min_to_dataframe(
        &self,
        market: Market,
        symbol: &str,
    ) -> Result<DataFrame, DataDirError> {
        Ok(parse_min_to_dataframe(self.min_path(market, symbol)?)?)
    }

    /// 从 datadir 发现并解析整个日线文件为结构体。
    pub fn parse_daily_file_to_structs(
        &self,
        market: Market,
        symbol: &str,
    ) -> Result<Vec<DailyKlineData>, DataDirError> {
        Ok(parse_daily_file_to_structs(self.day_path(market, symbol)?)?)
    }

    /// 从 datadir 发现并按字符串日期范围解析日线为结构体。
    pub fn parse_daily_to_structs(
        &self,
        market: Market,
        symbol: &str,
        start: &str,
        end: &str,
    ) -> Result<Vec<DailyKlineData>, DataDirError> {
        Ok(parse_daily_to_structs(
            self.day_path(market, symbol)?,
            start,
            end,
        )?)
    }

    /// 从 datadir 发现并按 typed 日期范围解析日线为结构体。
    pub fn parse_daily_to_structs_in_range(
        &self,
        market: Market,
        symbol: &str,
        start: Option<NaiveDate>,
        end: Option<NaiveDate>,
    ) -> Result<Vec<DailyKlineData>, DataDirError> {
        Ok(parse_daily_to_structs_in_range(
            self.day_path(market, symbol)?,
            start,
            end,
        )?)
    }

    /// 从 datadir 发现并解析整个日线文件为 `DataFrame`。
    #[cfg(feature = "polars")]
    pub fn parse_daily_file_to_dataframe(
        &self,
        market: Market,
        symbol: &str,
    ) -> Result<DataFrame, DataDirError> {
        Ok(parse_daily_file_to_dataframe(
            self.day_path(market, symbol)?,
        )?)
    }

    /// 从 datadir 发现并按字符串日期范围解析日线为 `DataFrame`。
    #[cfg(feature = "polars")]
    pub fn parse_daily_to_dataframe(
        &self,
        market: Market,
        symbol: &str,
        start: &str,
        end: &str,
    ) -> Result<DataFrame, DataDirError> {
        Ok(parse_daily_to_dataframe(
            self.day_path(market, symbol)?,
            start,
            end,
        )?)
    }

    /// 从 datadir 发现并按 typed 日期范围解析日线为 `DataFrame`。
    #[cfg(feature = "polars")]
    pub fn parse_daily_to_dataframe_in_range(
        &self,
        market: Market,
        symbol: &str,
        start: Option<NaiveDate>,
        end: Option<NaiveDate>,
    ) -> Result<DataFrame, DataDirError> {
        Ok(parse_daily_to_dataframe_in_range(
            self.day_path(market, symbol)?,
            start,
            end,
        )?)
    }

    /// 从 datadir 发现并读取财务文件。
    pub fn read_finance(
        &self,
        symbol: &str,
        file_type: FileType,
    ) -> Result<Vec<FinanceRecord>, DataDirError> {
        Ok(FinanceReader::read_file(
            self.finance_path(symbol, file_type)?,
        )?)
    }

    /// 从 datadir 发现并打开分红数据库。
    pub fn open_dividend_db(&self) -> Result<DividendDb, DataDirError> {
        Ok(DividendDb::new(self.dividend_db_path()?)?)
    }

    /// 从 datadir 发现并加载节假日列表。
    pub fn load_holidays(&self) -> Result<Vec<i64>, DataDirError> {
        Ok(load_holidays_from_root(&self.root)?)
    }

    /// 从 datadir 发现并加载 sector 名称。
    pub fn load_sector_names(&self) -> Result<Vec<String>, DataDirError> {
        Ok(load_sector_names_from_root(&self.root)?)
    }

    /// 从 datadir 发现并加载 `sectorlist.DAT`。
    pub fn load_sectorlist(&self) -> Result<Vec<String>, DataDirError> {
        Ok(load_sectorlist_from_root(&self.root)?)
    }

    /// 从 datadir 发现并加载全部 sector 成员映射。
    pub fn load_sector_weight_members(
        &self,
    ) -> Result<BTreeMap<String, Vec<String>>, DataDirError> {
        Ok(load_sector_weight_members_from_root(&self.root)?)
    }

    /// 从 datadir 发现并加载指定 sector/index 的权重映射。
    pub fn load_sector_weight_index(
        &self,
        index_code: &str,
    ) -> Result<BTreeMap<String, f64>, DataDirError> {
        validate_non_empty("index_code", index_code)?;
        Ok(load_sector_weight_index_from_root(&self.root, index_code)?)
    }

    /// 从 datadir 发现并加载行业成员映射。
    pub fn load_industry(&self) -> Result<BTreeMap<String, Vec<String>>, DataDirError> {
        Ok(load_industry_from_root(&self.root)?)
    }
}

fn validate_symbol(symbol: &str) -> Result<(), DataDirError> {
    validate_non_empty("symbol", symbol)
}

fn validate_date(date: &str) -> Result<(), DataDirError> {
    validate_non_empty("date", date)?;
    if date.len() != 8 || !date.chars().all(|ch| ch.is_ascii_digit()) {
        return Err(DataDirError::InvalidInput(format!(
            "date must be YYYYMMDD, got {date}"
        )));
    }
    Ok(())
}

fn validate_non_empty(field: &str, value: &str) -> Result<(), DataDirError> {
    if value.trim().is_empty() {
        return Err(DataDirError::InvalidInput(format!(
            "{field} cannot be empty"
        )));
    }
    Ok(())
}

fn first_existing(kind: &'static str, tried: Vec<PathBuf>) -> Result<PathBuf, DataDirError> {
    for path in &tried {
        if path.exists() {
            return Ok(path.clone());
        }
    }
    Err(DataDirError::PathNotFound { kind, tried })
}