38 lines
1.0 KiB
Rust
38 lines
1.0 KiB
Rust
use rand::rngs::ThreadRng;
|
|
use rand::thread_rng;
|
|
use rand::{distributions::Uniform, prelude::Distribution};
|
|
|
|
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
|
|
pub(crate) struct MarketModifier(f64);
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub(crate) struct MarketGenerator {
|
|
rng: ThreadRng,
|
|
sample_range: Uniform<f64>,
|
|
volatility: f64,
|
|
old_price: MarketModifier,
|
|
}
|
|
|
|
impl MarketGenerator {
|
|
pub(crate) fn new(volatility: f64, initial_value: f64) -> Self {
|
|
Self {
|
|
rng: thread_rng(),
|
|
sample_range: Uniform::new_inclusive(-0.5, 0.5),
|
|
volatility,
|
|
old_price: MarketModifier(initial_value),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Iterator for MarketGenerator {
|
|
type Item = MarketModifier;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
// Algorithm from https://stackoverflow.com/a/8597889
|
|
let rng_multiplier = self.sample_range.sample(&mut self.rng);
|
|
let delta = 2f64 * self.volatility * rng_multiplier;
|
|
self.old_price.0 += self.old_price.0 * delta;
|
|
Some(self.old_price)
|
|
}
|
|
}
|