use std::path::Path;
#[derive(Debug, Clone, Copy)]
pub struct Lc {
pub date: u16,
pub min: u16,
pub code: u32,
pub open: f32,
pub high: f32,
pub low: f32,
pub close: f32,
pub amount: f32,
pub vol: u32,
}
impl Lc {
pub fn from_bytes(code: u32, arr: &[u8]) -> Self {
use crate::bytes_helper::{f32_from_le_bytes, u16_from_le_bytes, u32_from_le_bytes};
Self {
date: u16_from_le_bytes(arr, 0),
min: u16_from_le_bytes(arr, 2),
open: f32_from_le_bytes(arr, 4),
high: f32_from_le_bytes(arr, 8),
low: f32_from_le_bytes(arr, 12),
close: f32_from_le_bytes(arr, 16),
amount: f32_from_le_bytes(arr, 20),
vol: u32_from_le_bytes(arr, 24),
code,
}
}
pub fn from_file_into_vec<P: AsRef<Path>>(code: u32, p: P) -> crate::Result<Vec<Lc>> {
Ok(std::fs::read(p)?
.chunks_exact(32)
.map(|b| Self::from_bytes(code, b))
.collect())
}
pub fn into_serde_type(self) -> LcSerde {
LcSerde {
datetime: self.datetime_string(),
code: format!("{:06}", self.code),
open: self.open,
high: self.high,
low: self.low,
close: self.close,
amount: self.amount,
vol: self.vol,
}
}
pub fn datetime_string(&self) -> String {
self.hm_arr()
.iter()
.fold(self.date_string(), |acc, &x| format!("{acc:02}:{x:02}"))
}
pub fn date_string(&self) -> String {
let [y, m, d] = self.ymd_arr();
let fill = |x: u16| if x > 9 { "" } else { "0" };
format!("{}-{}{}-{}{}", y, fill(m), m, fill(d), d)
}
pub fn ymd_arr(&self) -> [u16; 3] {
let x = self.date;
[x / 2048 + 2004, x % 2048 / 100, x % 2048 % 100]
}
pub fn hm_arr(&self) -> [u16; 2] {
[self.min / 60, self.min % 60]
}
pub fn datetime(&self) -> chrono::naive::NaiveDateTime {
use chrono::naive::NaiveDate;
const ERR: &str = "日期格式不对";
let [y, m, d] = self.ymd_arr();
let [h, min] = self.hm_arr();
NaiveDate::from_ymd_opt(y as i32, m as u32, d as u32)
.expect(ERR)
.and_hms_opt(h as u32, min as u32, 0)
.expect(ERR)
}
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct LcSerde {
pub datetime: String,
pub code: String,
pub open: f32,
pub high: f32,
pub low: f32,
pub close: f32,
pub amount: f32,
pub vol: u32,
}