trtr

Trading simulator and techanalysis gym
git clone https://git.ea.contact/trtr
Log | Files | Refs | README

data.rs (1210B)


      1 use std::fs::File;
      2 use std::io::BufReader;
      3 
      4 use flate2::read::GzDecoder;
      5 use serde::Serialize;
      6 
      7 #[derive(Clone, Serialize)]
      8 pub struct Candle {
      9     pub ts: i64,
     10     pub open: f64,
     11     pub high: f64,
     12     pub low: f64,
     13     pub close: f64,
     14     pub volume: f64,
     15 }
     16 
     17 pub struct AppData {
     18     pub candles: Vec<Candle>,
     19 }
     20 
     21 pub fn load_csv(path: &str) -> Result<Vec<Candle>, Box<dyn std::error::Error + Send + Sync>> {
     22     let file = File::open(path)?;
     23     let mut rdr = if path.ends_with(".gz") {
     24         csv::Reader::from_reader(Box::new(BufReader::new(GzDecoder::new(file))) as Box<dyn std::io::Read>)
     25     } else {
     26         csv::Reader::from_reader(Box::new(BufReader::new(file)) as Box<dyn std::io::Read>)
     27     };
     28     let mut candles = Vec::with_capacity(8_000_000);
     29 
     30     for result in rdr.records() {
     31         let rec = result?;
     32         let ts = rec[0].parse::<f64>()? as i64;
     33         let open = rec[1].parse::<f64>()?;
     34         let high = rec[2].parse::<f64>()?;
     35         let low = rec[3].parse::<f64>()?;
     36         let close = rec[4].parse::<f64>()?;
     37         let volume = rec[5].parse::<f64>()?;
     38         candles.push(Candle { ts, open, high, low, close, volume });
     39     }
     40 
     41     candles.shrink_to_fit();
     42     Ok(candles)
     43 }