finance-solution 0.5.0

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
//! # Parabolic SAR (Stop and Reverse)
//!
//! Classic Welles Wilder trailing stop:
//!
//! ```text
//! SAR_t = SAR_{t−1} + AF * (EP − SAR_{t−1})
//! ```
//!
//! with acceleration factor `AF` starting at `start`, stepping by `increment` up to `maximum`
//! when EP makes new extremes, and flipping long/short when price crosses SAR.
//!
//! Default: `(0.02, 0.02, 0.20)` ([`SarParams::standard`]).
//!
//! First bar is warm-up (`None`); SAR starts at bar 1.
//!
//! ---
//!
//! ## Trading perspective
//!
//! | Reading | Habit (classic) |
//! |---------|-----------------|
//! | SAR below price (dir +1) | Long / trail under |
//! | SAR above price (dir −1) | Short / trail over |
//! | Flip | Stop-and-reverse system signal |
//!
//! SAR is **aggressive** in chop (many flips). Often filtered by ADX or a slow MA.
//!
//! ## vs Supertrend
//!
//! | | SAR | Supertrend |
//! |--|-----|------------|
//! | Mechanism | AF toward extreme point | ATR bands around mid |
//! | Feel | Can hug price tightly | Smoother ATR trail |
//! | Choppy markets | Whipsaws more | Mult tuning helps |
//!
//! Many desks pick **one** primary trail (SAR *or* Supertrend), not both as simultaneous
//! entry signals.
//!
//! ## Pairs well with
//!
//! - **ADX** — only reverse with SAR when ADX shows trend (or only *enter* with SAR + ADX).
//! - **RSI** — avoid long SAR flips into overbought extremes without confirmation.
//! - **ATR** — independent stop size check (SAR distance ≠ risk budget).
//!
//! ---
//!
//! ## Engineering
//!
//! [`SarParams`] → [`sar`] / [`SarState`] → [`sar_solution`]. Batch via state.  
//! Initial long/short seed uses a simple first-bar extreme heuristic (documented convention;
//! platforms differ slightly on the very first flip).

use crate::stocks::ta::common::{opt_cell, require_hlc};
use crate::util::error::{require_finite, FinanceError, FinanceResult};
use crate::{columns_with_strings, print_table_locale_opt};

/// Parabolic SAR acceleration parameters.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SarParams {
    pub start: f64,
    pub increment: f64,
    pub maximum: f64,
}

impl SarParams {
    pub const fn new(start: f64, increment: f64, maximum: f64) -> Self {
        Self {
            start,
            increment,
            maximum,
        }
    }

    /// Classic `(0.02, 0.02, 0.20)`.
    pub const fn standard() -> Self {
        Self {
            start: 0.02,
            increment: 0.02,
            maximum: 0.20,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ValidatedSar {
    params: SarParams,
}

impl ValidatedSar {
    pub fn new(params: SarParams) -> FinanceResult<Self> {
        require_finite("start", params.start)?;
        require_finite("increment", params.increment)?;
        require_finite("maximum", params.maximum)?;
        if params.start <= 0.0 || params.increment <= 0.0 || params.maximum < params.start {
            return Err(FinanceError::Unsolvable {
                message: "SAR requires start>0, increment>0, maximum>=start",
            });
        }
        Ok(Self { params })
    }

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

    pub fn compute(self, high: &[f64], low: &[f64], close: &[f64]) -> FinanceResult<SarSeries> {
        sar_validated(high, low, close, self)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct SarSeries {
    pub sar: Vec<Option<f64>>,
    /// `+1` long (SAR below), `−1` short (SAR above) when defined.
    pub direction: Vec<Option<i8>>,
    pub params: SarParams,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SarBarOutput {
    pub sar: f64,
    pub direction: i8,
}

/// Incremental Parabolic SAR.
#[derive(Clone, Debug)]
pub struct SarState {
    params: SarParams,
    // After first bar setup:
    is_long: bool,
    af: f64,
    ep: f64,
    sar: f64,
    prev_high: f64,
    prev_low: f64,
    prev2_high: Option<f64>,
    prev2_low: Option<f64>,
    started: bool,
    last: Option<SarBarOutput>,
}

impl SarState {
    pub fn new(params: SarParams) -> FinanceResult<Self> {
        let _ = ValidatedSar::new(params)?;
        Ok(Self {
            params,
            is_long: true,
            af: params.start,
            ep: 0.0,
            sar: 0.0,
            prev_high: 0.0,
            prev_low: 0.0,
            prev2_high: None,
            prev2_low: None,
            started: false,
            last: None,
        })
    }

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

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

    pub fn reset(&mut self) {
        *self = Self::new(self.params).expect("params already valid");
    }

    pub fn push(&mut self, high: f64, low: f64, close: f64) -> FinanceResult<Option<SarBarOutput>> {
        require_finite("high", high)?;
        require_finite("low", low)?;
        require_finite("close", close)?;
        if high < low {
            return Err(FinanceError::InvalidCashflow {
                message: "high must be >= low for each bar",
            });
        }

        if !self.started {
            // Seed on first bar only (no SAR yet).
            self.prev_high = high;
            self.prev_low = low;
            self.started = true;
            self.last = None;
            return Ok(None);
        }

        if self.last.is_none() {
            // Initialize SAR at second bar from first bar extremes.
            self.is_long = close >= self.prev_high; // prefer long if ambiguous
            if high > self.prev_high {
                self.is_long = true;
            } else if low < self.prev_low {
                self.is_long = false;
            }
            if self.is_long {
                self.sar = self.prev_low;
                self.ep = high.max(self.prev_high);
            } else {
                self.sar = self.prev_high;
                self.ep = low.min(self.prev_low);
            }
            self.af = self.params.start;
            let dir = if self.is_long { 1 } else { -1 };
            let bar = SarBarOutput {
                sar: self.sar,
                direction: dir,
            };
            self.prev2_high = Some(self.prev_high);
            self.prev2_low = Some(self.prev_low);
            self.prev_high = high;
            self.prev_low = low;
            self.last = Some(bar);
            return Ok(Some(bar));
        }

        // Advance SAR
        let mut sar = self.sar + self.af * (self.ep - self.sar);

        if self.is_long {
            // SAR cannot be above prior two lows
            sar = sar.min(self.prev_low);
            if let Some(l2) = self.prev2_low {
                sar = sar.min(l2);
            }
            if low < sar {
                // flip to short
                self.is_long = false;
                sar = self.ep;
                self.ep = low;
                self.af = self.params.start;
            } else {
                if high > self.ep {
                    self.ep = high;
                    self.af = (self.af + self.params.increment).min(self.params.maximum);
                }
            }
        } else {
            sar = sar.max(self.prev_high);
            if let Some(h2) = self.prev2_high {
                sar = sar.max(h2);
            }
            if high > sar {
                // flip to long
                self.is_long = true;
                sar = self.ep;
                self.ep = high;
                self.af = self.params.start;
            } else if low < self.ep {
                self.ep = low;
                self.af = (self.af + self.params.increment).min(self.params.maximum);
            }
        }

        self.sar = sar;
        let dir = if self.is_long { 1 } else { -1 };
        let bar = SarBarOutput {
            sar,
            direction: dir,
        };
        self.prev2_high = Some(self.prev_high);
        self.prev2_low = Some(self.prev_low);
        self.prev_high = high;
        self.prev_low = low;
        self.last = Some(bar);
        Ok(Some(bar))
    }

    pub fn push_bars(
        &mut self,
        high: &[f64],
        low: &[f64],
        close: &[f64],
    ) -> FinanceResult<Vec<Option<SarBarOutput>>> {
        require_hlc(high, low, close)?;
        let mut out = Vec::with_capacity(close.len());
        for i in 0..close.len() {
            out.push(self.push(high[i], low[i], close[i])?);
        }
        Ok(out)
    }

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

pub fn sar(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    params: SarParams,
) -> FinanceResult<SarSeries> {
    ValidatedSar::new(params)?.compute(high, low, close)
}

fn sar_validated(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    eng: ValidatedSar,
) -> FinanceResult<SarSeries> {
    let mut st = SarState::new(eng.params)?;
    let bars = st.push_bars(high, low, close)?;
    let n = bars.len();
    let mut sar = vec![None; n];
    let mut direction = vec![None; n];
    for (i, b) in bars.into_iter().enumerate() {
        if let Some(bar) = b {
            sar[i] = Some(bar.sar);
            direction[i] = Some(bar.direction);
        }
    }
    Ok(SarSeries {
        sar,
        direction,
        params: eng.params,
    })
}

#[derive(Clone, Debug)]
pub struct SarSolution {
    series: SarSeries,
    close: Vec<f64>,
    formula: String,
}

impl SarSolution {
    pub fn series(&self) -> &SarSeries {
        &self.series
    }
    pub fn formula(&self) -> &str {
        &self.formula
    }

    pub fn print_table(&self) {
        self.print_table_locale_opt(None, None);
    }

    pub fn print_table_locale(&self, locale: &num_format::Locale, precision: usize) {
        self.print_table_locale_opt(Some(locale), Some(precision));
    }

    fn print_table_locale_opt(
        &self,
        locale: Option<&num_format::Locale>,
        precision: Option<usize>,
    ) {
        let columns = columns_with_strings(&[
            ("period", "i", true),
            ("close", "f", true),
            ("sar", "f", true),
            ("dir", "i", true),
        ]);
        let data = self
            .close
            .iter()
            .enumerate()
            .map(|(i, c)| {
                let d = self.series.direction[i]
                    .map(|x| x.to_string())
                    .unwrap_or_else(|| "n/a".to_string());
                vec![
                    i.to_string(),
                    c.to_string(),
                    opt_cell(self.series.sar[i]),
                    d,
                ]
            })
            .collect();
        print_table_locale_opt(&columns, data, locale, precision);
    }
}

/// # Examples
/// ```
/// use finance_solution::stocks::ta::{sar_solution, SarParams};
/// let n = 30usize;
/// let h: Vec<_> = (0..n).map(|i| 101.0 + i as f64 * 0.1).collect();
/// let l: Vec<_> = (0..n).map(|i| 99.0 + i as f64 * 0.1).collect();
/// let c: Vec<_> = (0..n).map(|i| 100.0 + i as f64 * 0.1).collect();
/// let sol = sar_solution(&h, &l, &c, SarParams::standard()).unwrap();
/// assert!(sol.formula().contains("0.02"));
/// ```
pub fn sar_solution(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    params: SarParams,
) -> FinanceResult<SarSolution> {
    let series = sar(high, low, close, params)?;
    Ok(SarSolution {
        series,
        close: close.to_vec(),
        formula: format!(
            "Parabolic SAR AF start={} step={} max={}",
            params.start, params.increment, params.maximum
        ),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn produces_sar() {
        let n = 40usize;
        let h: Vec<_> = (0..n).map(|i| 101.0 + i as f64 * 0.15).collect();
        let l: Vec<_> = (0..n).map(|i| 99.0 + i as f64 * 0.15).collect();
        let c: Vec<_> = (0..n).map(|i| 100.0 + i as f64 * 0.15).collect();
        let s = sar(&h, &l, &c, SarParams::standard()).unwrap();
        assert!(s.sar[0].is_none());
        assert!(s.sar[1].is_some());
        assert!(s.sar.iter().filter(|x| x.is_some()).count() > 20);
    }

    #[test]
    fn state_parity() {
        let n = 30usize;
        let h: Vec<_> = (0..n).map(|i| 12.0 + (i as f64 * 0.1).sin()).collect();
        let l: Vec<_> = (0..n).map(|i| 10.0 + (i as f64 * 0.1).sin()).collect();
        let c: Vec<_> = (0..n).map(|i| 11.0 + (i as f64 * 0.1).sin()).collect();
        let p = SarParams::standard();
        let batch = sar(&h, &l, &c, p).unwrap();
        let mut st = SarState::new(p).unwrap();
        for i in 0..n {
            let o = st.push(h[i], l[i], c[i]).unwrap();
            match (o, batch.sar[i], batch.direction[i]) {
                (None, None, None) => {}
                (Some(bar), Some(v), Some(d)) => {
                    assert!((bar.sar - v).abs() < 1e-9, "i={i}");
                    assert_eq!(bar.direction, d);
                }
                other => panic!("i={i}: {other:?}"),
            }
        }
    }

    #[test]
    fn bad_params_err() {
        assert!(ValidatedSar::new(SarParams::new(0.0, 0.02, 0.2)).is_err());
    }
}