Skip to content

Commit

Permalink
finished simple moving averate
Browse files Browse the repository at this point in the history
  • Loading branch information
zpeters committed Mar 9, 2021
1 parent cde7e01 commit 1e7ec5b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ this is from Mannings "Building a Stock-Tracking CLI With Async Streams in Rust"
4. Calculate performance indicators for the given period.
- **OK** A period is the time between the “from” date and the current date
- **OK** Aggregate the closing (adjclose) prices and find their minimum (fn min(series: &[f64]) -> Option<`f64`>) and maximum (fn max(series: &[f64]) -> Option<`f64`>) across the period. What data structures and types from the standard library can you use?
- Calculate a simple moving average over the entire series. Here is the recommended function interface: fn n_window_sma(n: usize, series: &[f64]) -> Option<Vec<`f64`>>, where the series parameter is a std::slice with one value per day.
- **OK** Calculate a simple moving average over the entire series. Here is the recommended function interface: fn n_window_sma(n: usize, series: &[f64]) -> Option<Vec<`f64`>>, where the series parameter is a std::slice with one value per day.


- Using the function interface fn price_diff(series: &[f64]) -> Option<(f64, f64)>, return two price differences: one as a percentage of the starting price, one as an absolute difference between the first and the last price of the period.

5. The company’s data pipeline expects a CSV file for input, so you decide to print the results in that format to stdout:
Expand Down
28 changes: 28 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ struct Stock {
quotes: Vec<yahoo::Quote>,
}

fn n_window_sma(n: usize, series: &[f64]) -> Option<Vec<f64>> {
if !series.is_empty() && n > 1 {
Some(
series
.windows(n)
.map(|w| w.iter().sum::<f64>() / w.len() as f64)
.collect(),
)
} else {
None
}
}

fn max(series: &[f64]) -> Option<f64> {
let mut max_found: Option<f64> = None;
for s in series.iter() {
Expand Down Expand Up @@ -159,4 +172,19 @@ mod tests {

assert_eq!(result, expected);
}

#[test]
fn test_n_window_sma() {
let input_usize: usize = 3;
let input_series: &[f64] = &[1.0, 2.0, 3.5, 4.5, 12.2];
let expected = Some(vec![
2.1666666666666665,
3.3333333333333335,
6.733333333333333,
]);

let actual = n_window_sma(input_usize, input_series);

assert_eq!(actual, expected);
}
}

0 comments on commit 1e7ec5b

Please sign in to comment.