From 5e856a3c09a8bb6d71770db52fbc3db4ec570e19 Mon Sep 17 00:00:00 2001 From: ryqdev Date: Sat, 1 Jun 2024 14:52:56 +0800 Subject: [PATCH] add csv mode --- src/csv/csv.rs | 33 +++++++++++++++++++++++++++++++++ src/csv/mod.rs | 1 + src/lib.rs | 32 ++------------------------------ 3 files changed, 36 insertions(+), 30 deletions(-) create mode 100644 src/csv/csv.rs create mode 100644 src/csv/mod.rs diff --git a/src/csv/csv.rs b/src/csv/csv.rs new file mode 100644 index 0000000..40a7916 --- /dev/null +++ b/src/csv/csv.rs @@ -0,0 +1,33 @@ +use std::fs::File; +use time::OffsetDateTime; +use crate::{Bar}; + + +#[derive(Debug, serde::Deserialize, PartialEq)] +struct CSVData { + date: String, + open: f64, + high: f64, + low: f64, + close: f64 +} + +// https://docs.rs/csv/latest/csv/struct.Reader.html +pub fn get_bar_from_csv(symbol: &str) -> Result, Box> { + csv::ReaderBuilder::new() + .has_headers(true) + .from_reader( File::open(format!("data/{symbol}.csv"))?) + .deserialize::().map(|line| { + let record = line?; + Ok(Bar { + date: OffsetDateTime::now_utc(), + open: record.open, + high: record.high, + low: record.low, + close: record.close, + volume: 0.0, + wap: 0.0, + count: 0, + }) + }).collect() +} diff --git a/src/csv/mod.rs b/src/csv/mod.rs new file mode 100644 index 0000000..dd07493 --- /dev/null +++ b/src/csv/mod.rs @@ -0,0 +1 @@ +pub(crate) mod csv; \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 4a8ac7f..f357a6c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ pub mod broker; mod analyzer; mod visualization; pub mod strategy; +mod csv; use std::fs::File; @@ -132,7 +133,7 @@ impl Golden for BackTestGolden { fn set_data_feed(&mut self, symbol: &str) -> &mut dyn Golden{ log::info!("set data feed for {}", symbol); - self.data = get_bar_from_csv(symbol).unwrap(); + self.data = csv::csv::get_bar_from_csv(symbol).unwrap(); self } fn set_broker(&mut self, cash: f64) -> &mut dyn Golden { @@ -195,34 +196,5 @@ pub struct Bar { pub count: i32, } -#[derive(Debug, serde::Deserialize, PartialEq)] -struct CSVData { - date: String, - open: f64, - high: f64, - low: f64, - close: f64 -} - -// https://docs.rs/csv/latest/csv/struct.Reader.html -pub fn get_bar_from_csv(symbol: &str) -> Result, Box> { - csv::ReaderBuilder::new() - .has_headers(true) - .from_reader( File::open(format!("data/{symbol}.csv"))?) - .deserialize::().map(|line| { - let record = line?; - Ok(Bar { - date: OffsetDateTime::now_utc(), - open: record.open, - high: record.high, - low: record.low, - close: record.close, - volume: 0.0, - wap: 0.0, - count: 0, - }) - }).collect() -} - // fn connect_and_fetch_market_data() -> impl Iterator{ // \ No newline at end of file