finance-solution 0.5.1

Finance math: TVM, cashflow, amortization, equity path metrics, technical analysis (SMA/EMA/WMA/HMA/RMA/DEMA/TEMA/KAMA/MACD, BB/Keltner/Donchian/Stoch/VWAP/RVOL/RSI/ATR/LinReg, WillR/OBV/CCI/ADX/MOM/MFI/Supertrend/SAR), risk (Sharpe/Sortino/Calmar/Ulcer/IR), and options (BSM, Black76, GK, CRR American) with Result-only APIs and incremental state.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! # Advanced moving averages: DEMA, TEMA, RMA (Wilder), KAMA
//!
//! Smoothers beyond SMA/EMA/WMA/HMA. Same API layers: free batch + `*State` +
//! (for KAMA) [`KamaParams`].
//!
//! | Name | Formula sketch | vs SMA/EMA | Typical use |
//! |------|----------------|------------|-------------|
//! | **RMA / Wilder** | α = 1/n; seed SMA | **Slower** than EMA(α=2/(n+1)); same family as RSI/ATR smoothers | Match Wilder indicators; “SMMA” on some platforms |
//! | **DEMA** | `2·EMA − EMA(EMA)` | **Faster** / less lag than EMA of same period | Trend follow when EMA feels late |
//! | **TEMA** | `3·e1 − 3·e2 + e3` | Still more lag reduction than DEMA | Aggressive smooth; longer warm-up |
//! | **KAMA** | ER scales SC between fast/slow EMA constants | **Adaptive**: quiet → slow; trending → fast | Choppy markets where fixed EMA whipsaws |
//!
//! ## When to pick which
//!
//! | Goal | Prefer | Avoid / caution |
//! |------|--------|-----------------|
//! | Classic chart MA | SMA / EMA | TEMA until you need speed |
//! | Less lag than EMA | DEMA → TEMA | TEMA needs ~3× period warm-up bars |
//! | Same math as RSI/ATR | **RMA** | Using EMA(14) and calling it Wilder |
//! | Regime-adaptive | **KAMA** | Expecting a fixed “period feel” |
//!
//! ## Pairing for stock signals (illustrative, not advice)
//!
//! - **DEMA/TEMA** + **ADX**: only take MA crossovers when ADX shows trend strength.
//! - **KAMA** + **ATR/Supertrend**: adaptive midline + volatility stop.
//! - **RMA** + **RSI**: both Wilder-family; consistent smoothing philosophy.
//! - Fast/slow **EMA** still the default for MACD-style spreads; DEMA/TEMA are optional legs.
//!
//! ## Engineering
//!
//! Batch free functions use the matching `*State` end-to-end.  
//! KAMA first value when the ER window fills is **seeded to price** (common convention).
//!
//! Defaults: RMA/DEMA/TEMA period often **20** in call sites; KAMA **(10, 2, 30)**.

use crate::stocks::ta::common::validate_series;
use crate::stocks::ta::moving_average::EmaState;
use crate::stocks::ta::ring::RingF64;
use crate::util::error::{require_finite, FinanceError, FinanceResult};
use crate::util::primitives::PeriodLength;

// ---------------------------------------------------------------------------
// RMA (Wilder / SMMA)
// ---------------------------------------------------------------------------

/// Incremental Wilder RMA (also called SMMA). α = 1/`period`.
///
/// Use when you want the same recursive smoother as Wilder RSI/ATR, not EMA’s 2/(n+1).
#[derive(Clone, Debug)]
pub struct RmaState {
    period: usize,
    alpha: f64,
    seed: RingF64,
    value: Option<f64>,
}

impl RmaState {
    pub fn new(period: usize) -> FinanceResult<Self> {
        let period = PeriodLength::new(period)?.get();
        Ok(Self {
            period,
            alpha: 1.0 / period as f64,
            seed: RingF64::with_capacity(period),
            value: None,
        })
    }

    pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
        let mut s = Self::new(period)?;
        s.push_bars(closes)?;
        Ok(s)
    }

    pub fn period(&self) -> usize {
        self.period
    }

    pub fn reset(&mut self) {
        self.seed.clear();
        self.value = None;
    }

    pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
        require_finite("close", close)?;
        if let Some(prev) = self.value {
            let next = self.alpha * close + (1.0 - self.alpha) * prev;
            self.value = Some(next);
            return Ok(Some(next));
        }
        let _ = self.seed.push(close);
        if self.seed.is_full() {
            let seed = self.seed.sum() / self.period as f64;
            self.value = Some(seed);
            Ok(Some(seed))
        } else {
            Ok(None)
        }
    }

    pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
        let mut out = Vec::with_capacity(closes.len());
        for &c in closes {
            out.push(self.push(c)?);
        }
        Ok(out)
    }

    pub fn last(&self) -> Option<f64> {
        self.value
    }
}

/// Wilder RMA / SMMA of `period` closes.
pub fn rma(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
    validate_series("close", closes)?;
    let mut st = RmaState::new(period)?;
    st.push_bars(closes)
}

pub fn rma_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
    let mut st = RmaState::new(period)?;
    for &c in closes {
        st.push(c)?;
    }
    Ok(st.last())
}

// ---------------------------------------------------------------------------
// DEMA
// ---------------------------------------------------------------------------

/// Double exponential moving average: `2·EMA − EMA(EMA)`.
///
/// Reduces lag vs a single EMA of the same period (Mulloy). Warm-up is longer (nested EMA).
#[derive(Clone, Debug)]
pub struct DemaState {
    e1: EmaState,
    e2: EmaState,
}

impl DemaState {
    pub fn new(period: usize) -> FinanceResult<Self> {
        Ok(Self {
            e1: EmaState::new(period)?,
            e2: EmaState::new(period)?,
        })
    }

    pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
        let mut s = Self::new(period)?;
        s.push_bars(closes)?;
        Ok(s)
    }

    pub fn period(&self) -> usize {
        self.e1.period()
    }

    pub fn reset(&mut self) {
        self.e1.reset();
        self.e2.reset();
    }

    pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
        let e1 = match self.e1.push(close)? {
            Some(v) => v,
            None => return Ok(None),
        };
        match self.e2.push(e1)? {
            Some(e2) => Ok(Some(2.0 * e1 - e2)),
            None => Ok(None),
        }
    }

    pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
        let mut out = Vec::with_capacity(closes.len());
        for &c in closes {
            out.push(self.push(c)?);
        }
        Ok(out)
    }

    pub fn last(&self) -> Option<f64> {
        match (self.e1.last(), self.e2.last()) {
            (Some(e1), Some(e2)) => Some(2.0 * e1 - e2),
            _ => None,
        }
    }
}

/// DEMA of `period` closes.
pub fn dema(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
    validate_series("close", closes)?;
    let mut st = DemaState::new(period)?;
    st.push_bars(closes)
}

pub fn dema_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
    let mut st = DemaState::new(period)?;
    for &c in closes {
        st.push(c)?;
    }
    Ok(st.last())
}

// ---------------------------------------------------------------------------
// TEMA
// ---------------------------------------------------------------------------

/// Triple exponential moving average: `3·e1 − 3·e2 + e3`.
///
/// Further lag reduction vs DEMA; longest warm-up of the EMA-family stack here.
#[derive(Clone, Debug)]
pub struct TemaState {
    e1: EmaState,
    e2: EmaState,
    e3: EmaState,
}

impl TemaState {
    pub fn new(period: usize) -> FinanceResult<Self> {
        Ok(Self {
            e1: EmaState::new(period)?,
            e2: EmaState::new(period)?,
            e3: EmaState::new(period)?,
        })
    }

    pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
        let mut s = Self::new(period)?;
        s.push_bars(closes)?;
        Ok(s)
    }

    pub fn period(&self) -> usize {
        self.e1.period()
    }

    pub fn reset(&mut self) {
        self.e1.reset();
        self.e2.reset();
        self.e3.reset();
    }

    pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
        let e1 = match self.e1.push(close)? {
            Some(v) => v,
            None => return Ok(None),
        };
        let e2 = match self.e2.push(e1)? {
            Some(v) => v,
            None => return Ok(None),
        };
        match self.e3.push(e2)? {
            Some(e3) => Ok(Some(3.0 * e1 - 3.0 * e2 + e3)),
            None => Ok(None),
        }
    }

    pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
        let mut out = Vec::with_capacity(closes.len());
        for &c in closes {
            out.push(self.push(c)?);
        }
        Ok(out)
    }

    pub fn last(&self) -> Option<f64> {
        match (self.e1.last(), self.e2.last(), self.e3.last()) {
            (Some(e1), Some(e2), Some(e3)) => Some(3.0 * e1 - 3.0 * e2 + e3),
            _ => None,
        }
    }
}

/// TEMA of `period` closes.
pub fn tema(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
    validate_series("close", closes)?;
    let mut st = TemaState::new(period)?;
    st.push_bars(closes)
}

pub fn tema_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
    let mut st = TemaState::new(period)?;
    for &c in closes {
        st.push(c)?;
    }
    Ok(st.last())
}

// ---------------------------------------------------------------------------
// KAMA
// ---------------------------------------------------------------------------

/// Kaufman Adaptive Moving Average parameters.
///
/// Efficiency ratio over `period` maps between `fast` and `slow` EMA-style smoothing
/// constants. Classic desk pack: [`KamaParams::standard`] `(10, 2, 30)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct KamaParams {
    /// Efficiency-ratio lookback (typically 10).
    pub period: usize,
    /// Fast EMA-equivalent period (typically 2).
    pub fast: usize,
    /// Slow EMA-equivalent period (typically 30).
    pub slow: usize,
}

impl KamaParams {
    pub const fn new(period: usize, fast: usize, slow: usize) -> Self {
        Self { period, fast, slow }
    }

    /// Classic `(10, 2, 30)`.
    pub const fn standard() -> Self {
        Self {
            period: 10,
            fast: 2,
            slow: 30,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ValidatedKama {
    params: KamaParams,
}

impl ValidatedKama {
    pub fn new(params: KamaParams) -> FinanceResult<Self> {
        PeriodLength::new(params.period)?;
        PeriodLength::new(params.fast)?;
        PeriodLength::new(params.slow)?;
        if params.fast >= params.slow {
            return Err(FinanceError::Unsolvable {
                message: "KAMA requires fast < slow",
            });
        }
        Ok(Self { params })
    }

    pub fn params(self) -> KamaParams {
        self.params
    }

    pub fn compute(self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
        kama(closes, self.params)
    }
}

/// Incremental KAMA.
///
/// First defined bar seeds KAMA to the current price; thereafter  
/// `KAMA += SC²-scaled step toward price` with SC from the efficiency ratio.
#[derive(Clone, Debug)]
pub struct KamaState {
    params: KamaParams,
    fast_sc: f64,
    slow_sc: f64,
    /// Rolling window of `period + 1` closes for ER (change over `period` steps).
    closes: RingF64,
    kama: Option<f64>,
    last: Option<f64>,
}

impl KamaState {
    pub fn new(params: KamaParams) -> FinanceResult<Self> {
        let _ = ValidatedKama::new(params)?;
        let fast_sc = 2.0 / (params.fast as f64 + 1.0);
        let slow_sc = 2.0 / (params.slow as f64 + 1.0);
        Ok(Self {
            params,
            fast_sc,
            slow_sc,
            closes: RingF64::with_capacity(params.period + 1),
            kama: None,
            last: None,
        })
    }

    pub fn from_history(params: KamaParams, closes: &[f64]) -> FinanceResult<Self> {
        let mut s = Self::new(params)?;
        s.push_bars(closes)?;
        Ok(s)
    }

    pub fn params(&self) -> KamaParams {
        self.params
    }

    pub fn reset(&mut self) {
        self.closes.clear();
        self.kama = None;
        self.last = None;
    }

    pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
        require_finite("close", close)?;
        let _ = self.closes.push(close);
        // Need period+1 samples for ER over `period` steps
        if self.closes.len() < self.params.period + 1 {
            self.last = None;
            return Ok(None);
        }
        let mut ordered = Vec::with_capacity(self.params.period + 1);
        self.closes.copy_ordered(&mut ordered);
        let n = ordered.len();
        let change = (ordered[n - 1] - ordered[0]).abs();
        let mut volatility = 0.0;
        for i in 1..n {
            volatility += (ordered[i] - ordered[i - 1]).abs();
        }
        let er = if volatility > 0.0 {
            change / volatility
        } else {
            0.0
        };
        let sc = (er * (self.fast_sc - self.slow_sc) + self.slow_sc).powi(2);
        let kama = match self.kama {
            None => close, // first KAMA = price when ER window first fills
            Some(prev) => prev + sc * (close - prev),
        };
        self.kama = Some(kama);
        self.last = Some(kama);
        Ok(Some(kama))
    }

    pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
        validate_series("close", closes)?;
        let mut out = Vec::with_capacity(closes.len());
        for &c in closes {
            out.push(self.push(c)?);
        }
        Ok(out)
    }

    pub fn last(&self) -> Option<f64> {
        self.last
    }
}

/// Kaufman adaptive moving average.
pub fn kama(closes: &[f64], params: KamaParams) -> FinanceResult<Vec<Option<f64>>> {
    let mut st = KamaState::new(params)?;
    st.push_bars(closes)
}

pub fn kama_last(closes: &[f64], params: KamaParams) -> FinanceResult<Option<f64>> {
    let mut st = KamaState::new(params)?;
    for &c in closes {
        st.push(c)?;
    }
    Ok(st.last())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::stocks::ta::moving_average::ema;

    #[test]
    fn rma_matches_wilder_seed() {
        let c: Vec<_> = (1..=20).map(|x| x as f64).collect();
        let r = rma(&c, 5).unwrap();
        // First RMA at index 4 = SMA(1..5)=3
        assert!((r[4].unwrap() - 3.0).abs() < 1e-12);
        // Next: (3*4 + 6)/5 = 3.6
        assert!((r[5].unwrap() - 3.6).abs() < 1e-12);
    }

    #[test]
    fn dema_related_to_ema() {
        let c: Vec<_> = (1..=40).map(|x| x as f64).collect();
        let d = dema(&c, 5).unwrap();
        let e1 = ema(&c, 5).unwrap();
        // DEMA should be defined later than EMA
        let first_e = e1.iter().position(|x| x.is_some()).unwrap();
        let first_d = d.iter().position(|x| x.is_some()).unwrap();
        assert!(first_d >= first_e);
        assert!(d.last().unwrap().is_some());
    }

    #[test]
    fn tema_runs() {
        let c: Vec<_> = (1..=50).map(|x| 100.0 + x as f64 * 0.1).collect();
        let t = tema(&c, 5).unwrap();
        assert!(t.iter().filter(|x| x.is_some()).count() > 10);
    }

    #[test]
    fn kama_standard_runs() {
        let c: Vec<_> = (0..40).map(|i| 100.0 + (i as f64).sin() * 2.0).collect();
        let k = kama(&c, KamaParams::standard()).unwrap();
        assert!(k[9].is_none() || k[10].is_some()); // first at period (index period)
        assert!(k.last().unwrap().is_some());
    }

    #[test]
    fn dema_tema_state_parity() {
        let c: Vec<_> = (0..45).map(|i| 50.0 + i as f64 * 0.25).collect();
        for (batch, mut st) in [(dema(&c, 8).unwrap(), DemaState::new(8).unwrap())] {
            for i in 0..c.len() {
                let o = st.push(c[i]).unwrap();
                match (o, batch[i]) {
                    (None, None) => {}
                    (Some(a), Some(b)) => assert!((a - b).abs() < 1e-9),
                    other => panic!("{other:?}"),
                }
            }
        }
        let batch = tema(&c, 6).unwrap();
        let mut st = TemaState::new(6).unwrap();
        for i in 0..c.len() {
            let o = st.push(c[i]).unwrap();
            match (o, batch[i]) {
                (None, None) => {}
                (Some(a), Some(b)) => assert!((a - b).abs() < 1e-9),
                other => panic!("{other:?}"),
            }
        }
        let batch = rma(&c, 7).unwrap();
        let mut st = RmaState::new(7).unwrap();
        for i in 0..c.len() {
            let o = st.push(c[i]).unwrap();
            match (o, batch[i]) {
                (None, None) => {}
                (Some(a), Some(b)) => assert!((a - b).abs() < 1e-9),
                other => panic!("{other:?}"),
            }
        }
        let p = KamaParams::standard();
        let batch = kama(&c, p).unwrap();
        let mut st = KamaState::new(p).unwrap();
        for i in 0..c.len() {
            let o = st.push(c[i]).unwrap();
            match (o, batch[i]) {
                (None, None) => {}
                (Some(a), Some(b)) => assert!((a - b).abs() < 1e-9),
                other => panic!("{other:?}"),
            }
        }
    }

    #[test]
    fn kama_fast_ge_slow_err() {
        assert!(ValidatedKama::new(KamaParams::new(10, 30, 2)).is_err());
    }
}