Skip to content

Commit

Permalink
Add interval to results.csv
Browse files Browse the repository at this point in the history
  • Loading branch information
noahbclarkson committed Nov 15, 2024
1 parent 20872c6 commit 3bc1289
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 24 deletions.
14 changes: 12 additions & 2 deletions src/algorithm/algo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,10 @@ fn backtest(
debug!("Cross Validation {}: {}", i + 1, test_data);
test_datas.push(test_data);
}
let returns = test_datas.iter().map(|d| d.monthly_return).collect::<Vec<f64>>();
let returns = test_datas
.iter()
.map(|d| d.monthly_return)
.collect::<Vec<f64>>();
let accuracies = test_datas.iter().map(|d| d.accuracy).collect::<Vec<f64>>();
let median_return = returns[returns.len() / 2];
let median_accuracy = accuracies[accuracies.len() / 2];
Expand Down Expand Up @@ -147,7 +150,14 @@ fn get_overall_dataset(
.iter()
.map(|r| {
r.iter()
.map(|v| if v.is_nan() { 0.0 } else { *v })
.map(|v| {
if v.is_nan() {
debug!("Found NaN value");
0.0
} else {
*v
}
})
.collect()
})
.collect();
Expand Down
4 changes: 2 additions & 2 deletions src/algorithm/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod pls;
pub mod algo;
pub mod test_data;
pub mod pls;
pub mod test_data;
26 changes: 16 additions & 10 deletions src/data/candlestick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,12 @@ pub struct Candlestick {
}

impl Candlestick {

// Create a new Candlestick from a KlineSummary
// Create a new Candlestick from a KlineSummary
//
// # Arguments
//
// * `summary` - The KlineSummary to convert to a Candlestick.
//
//
// # Returns
//
// A Result containing the Candlestick if successful, or a KryptoError if an error occurred.
Expand All @@ -33,12 +32,13 @@ impl Candlestick {
timestamp: summary.open_time,
},
)?;
let close_time = Utc.timestamp_millis_opt(summary.close_time).single().ok_or(
KryptoError::InvalidCandlestickDateTime {
let close_time = Utc
.timestamp_millis_opt(summary.close_time)
.single()
.ok_or(KryptoError::InvalidCandlestickDateTime {
when: When::Close,
timestamp: summary.close_time,
},
)?;
})?;
if let Some(std::cmp::Ordering::Greater) = open_time.partial_cmp(&close_time) {
return Err(KryptoError::OpenTimeGreaterThanCloseTime {
open_time: summary.open_time,
Expand Down Expand Up @@ -164,8 +164,14 @@ mod tests {
};

let candlestick = Candlestick::from_summary(summary).unwrap();
assert_eq!(candlestick.open_time, Utc.timestamp_millis_opt(1618185600000).single().unwrap());
assert_eq!(candlestick.close_time, Utc.timestamp_millis_opt(1618185659999).single().unwrap());
assert_eq!(
candlestick.open_time,
Utc.timestamp_millis_opt(1618185600000).single().unwrap()
);
assert_eq!(
candlestick.close_time,
Utc.timestamp_millis_opt(1618185659999).single().unwrap()
);
assert_eq!(candlestick.open, 0.0);
assert_eq!(candlestick.high, 0.0);
assert_eq!(candlestick.low, 0.0);
Expand Down Expand Up @@ -250,4 +256,4 @@ mod tests {
})
);
}
}
}
2 changes: 1 addition & 1 deletion src/data/dataset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl IntervalData {
self.symbol_data_map.is_empty()
}

// Get all the technicals for all the symbols. Each row contains all the tecnhicals for each of
// Get all the technicals for all the symbols. Each row contains all the tecnhicals for each of
// the symbols at a given time.
pub fn get_records(&self) -> Vec<Vec<f64>> {
let mut records = Vec::new();
Expand Down
28 changes: 21 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use core::f64;

use krypto::{
algorithm::algo::Algorithm, config::KryptoConfig, data::{dataset::Dataset, technicals::TECHNICAL_COUNT}, error::KryptoError,
algorithm::algo::Algorithm,
config::KryptoConfig,
data::{dataset::Dataset, technicals::TECHNICAL_COUNT},
error::KryptoError,
logging::setup_tracing,
};
use tracing::info;
Expand All @@ -22,8 +25,17 @@ fn run() -> Result<(), KryptoError> {
let mut best_return = f64::NEG_INFINITY;
let mut best_algorithm = None;
let mut i = 0;
let mut csv = csv::Writer::from_path("results.csv").map_err(|e| KryptoError::CsvError(e.to_string()))?;
csv.write_record(["n", "depth", "ticker", "monthly_return", "accuracy"]).map_err(|e| KryptoError::CsvError(e.to_string()))?;
let mut csv =
csv::Writer::from_path("results.csv").map_err(|e| KryptoError::CsvError(e.to_string()))?;
csv.write_record([
"n",
"depth",
"ticker",
"monthly_return",
"accuracy",
"interval",
])
.map_err(|e| KryptoError::CsvError(e.to_string()))?;
for (interval, interval_data) in dataset.get_map() {
info!("Interval: {}", interval);
for symbol in interval_data.keys() {
Expand All @@ -45,16 +57,18 @@ fn run() -> Result<(), KryptoError> {
symbol.to_string(),
algorithm.get_monthly_return().to_string(),
algorithm.get_accuracy().to_string(),
]).map_err(|e| KryptoError::CsvError(e.to_string()))?;
csv.flush().map_err(|e| KryptoError::CsvError(e.to_string()))?;
interval.to_string(),
])
.map_err(|e| KryptoError::CsvError(e.to_string()))?;
csv.flush()
.map_err(|e| KryptoError::CsvError(e.to_string()))?;
i += 1;
algorithms.push(algorithm);

}
}
}
}
let best_algorithm = algorithms.get(best_algorithm.unwrap());
info!("Best Algorithm: {}", &best_algorithm.unwrap());
info!("Best Algorithm: {}", &best_algorithm.unwrap());
Ok(())
}
2 changes: 1 addition & 1 deletion src/util/date_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,4 @@ pub fn days_between(start: NaiveDate, end: NaiveDate) -> i64 {

pub fn days_between_datetime(start: DateTime<Utc>, end: DateTime<Utc>) -> i64 {
(end - start).num_days()
}
}
2 changes: 1 addition & 1 deletion src/util/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod date_utils;
pub mod matrix_utils;
pub mod matrix_utils;

0 comments on commit 3bc1289

Please sign in to comment.