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
#![allow(dead_code)]

use std::collections::VecDeque;
use std::fmt;

use crate::errors::*;
use crate::{Close, High, Low, Next, Reset, Volume};

use crate::{Factory};
use crate::indicators::SimpleMovingAverage;

pub struct MfiFactory {
}

impl MfiFactory {
    pub fn new() -> Self {
        Self{}
    }
}

impl Factory for MfiFactory {
    fn create() -> Box<dyn Next<f64, Output = Box<[f64]>>> {
        Box::new(SimpleMovingAverage::default())
    }
}

/// Money Flow Index (MFI).
///
/// The MFI is an volume and price based oscillator which gives moneyflow over n periods.
/// MFI is used to measure buying and selling pressure.
/// MFI is also known as volume-weighted RSI.
///
/// # Formula
///
/// Typical Price(TP) = (High + Low + Close)/3
///
/// Money Flow(MF) = Typical Price x Volume
///
/// MF is positive when currennt TP is greater that previous period TP and
/// negative when current TP is less than preivous TP.
///
/// Positive money flow (PMF)- calculated by adding the money flow of all the days RMF is positive.
///
/// Negative money flow (NMF)- calculated by adding the money flow of all the days RMF is negative.
///
/// Money Flow Index(MFI) = PMF / (PMF + NMF) * 100
///
///
/// # Parameters
///
/// * _n_ - number of periods, integer greater than 0
///
/// # Example
///
/// ```
/// use core::indicators::MoneyFlowIndex;
/// use core::{Next, DataItem};
///
/// let mut mfi = MoneyFlowIndex::new(3).unwrap();
/// let di = DataItem::builder()
///             .high(3.0)
///             .low(1.0)
///             .close(2.0)
///             .open(1.5)
///             .volume(1000.0)
///             .build().unwrap();
/// mfi.next(&di);
///
/// ```
/// # Links
/// * [Money Flow Index, Wikipedia](https://en.wikipedia.org/wiki/Money_flow_index)
/// * [Money Flow Index, stockcharts](https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:money_flow_index_mfi)

#[derive(Debug, Clone)]
pub struct MoneyFlowIndex {
    n: u32,
    money_flows: VecDeque<f64>,
    prev_typical_price: f64,
    total_positive_money_flow: f64,
    total_absolute_money_flow: f64,
    is_new: bool,
}

impl MoneyFlowIndex {
    pub fn new(n: u32) -> Result<Self> {
        match n {
            0 => Err(Error::from_kind(ErrorKind::InvalidParameter)),
            _ => {
                let indicator = Self {
                    n: n,
                    money_flows: VecDeque::with_capacity(n as usize + 1),
                    prev_typical_price: 0.0,
                    total_positive_money_flow: 0.0,
                    total_absolute_money_flow: 0.0,
                    is_new: true,
                };
                Ok(indicator)
            }
        }
    }
}

impl<'a, T: High + Low + Close + Volume> Next<&'a T> for MoneyFlowIndex {
    type Output = f64;

    fn next(&mut self, input: &'a T) -> f64 {
        let typical_price = (input.high() + input.low() + input.close()) / 3.0;

        if self.is_new {
            // money flow is 0, because without having previous typical_price
            // it is not possible to determine is it positive or negative.
            self.money_flows.push_back(0.0);
            self.prev_typical_price = typical_price;
            self.is_new = false;
            return 50.0;
        } else {
            let money_flow = typical_price * input.volume();

            let signed_money_flow = if typical_price >= self.prev_typical_price {
                self.total_positive_money_flow += money_flow;
                money_flow
            } else {
                -money_flow
            };

            self.total_absolute_money_flow += money_flow;

            if self.money_flows.len() == (self.n as usize) {
                let old_signed_money_flow = self.money_flows.pop_front().unwrap();
                if old_signed_money_flow > 0.0 {
                    self.total_positive_money_flow -= old_signed_money_flow;
                    self.total_absolute_money_flow -= old_signed_money_flow;
                } else {
                    // it is actually subtraction, because old_signed_money_flow is negative
                    self.total_absolute_money_flow += old_signed_money_flow;
                }
            }

            self.money_flows.push_back(signed_money_flow);
            self.prev_typical_price = typical_price;

            (self.total_positive_money_flow / self.total_absolute_money_flow) * 100.0
        }
    }
}

impl Default for MoneyFlowIndex {
    fn default() -> Self {
        Self::new(14).unwrap()
    }
}

impl fmt::Display for MoneyFlowIndex {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "MFI({})", self.n)
    }
}

impl Reset for MoneyFlowIndex {
    fn reset(&mut self) {
        self.money_flows.clear();
        self.prev_typical_price = 0.0;
        self.total_positive_money_flow = 0.0;
        self.total_absolute_money_flow = 0.0;
        self.is_new = true;
    }
}

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

    #[test]
    fn test_new() {
        assert!(MoneyFlowIndex::new(0).is_err());
        assert!(MoneyFlowIndex::new(1).is_ok());
    }

    #[test]
    fn test_next_bar() {
        let mut mfi = MoneyFlowIndex::new(3).unwrap();

        // tp = 2.0
        let bar1 = Bar::new().high(3).low(1).close(2).volume(500.0);
        assert_eq!(mfi.next(&bar1), 50.0);

        // tp = 2.2, fm = 2.2*1000 = 2200, abs_total = 2200, pos_total = 2200
        let bar2 = Bar::new().high(2.3).low(2.0).close(2.3).volume(1000.0);
        assert_eq!(mfi.next(&bar2), 100.0);

        // tp = 8.0, fm = 8*200 = 1600, abs_total = 3800, pos_total = 3800
        let bar3 = Bar::new().high(9).low(7).close(8).volume(200.0);
        assert_eq!(mfi.next(&bar3), 100.0);

        // tp = 4.0, fm = -4.0*500 = -2000, abs_total = 5800 , pos_total = 3800
        let bar4 = Bar::new().high(5).low(3).close(4).volume(500.0);
        assert_eq!(mfi.next(&bar4), 3800.0 / 5800.0 * 100.0);

        // tp = 3.0, fm = -3 * 5000 = -15000, abs_total = 5800+15000-2200=18600, pos_total=3800-2200=1600
        let bar5 = Bar::new().high(4).low(2).close(3).volume(5000.0);
        assert_eq!(mfi.next(&bar5), 1600.0 / 18600.0 * 100.0);

        // tp = 1.5, fm = -1.5*6000= -9000, abs_total=18600+9000-1600=26000, pos_total=0
        let bar6 = Bar::new().high(2).low(1).close(1.5).volume(6000.0);
        assert_eq!(mfi.next(&bar6), 0.0 / 23800.0 * 100.0);

        // tp = 2, fm = 2*7000=14000, abs_total=26000+14000-2000=38000, pos_total=14000
        let bar7 = Bar::new().high(2).low(2).close(2).volume(7000.0);
        assert_eq!(mfi.next(&bar7), 14000.0 / 38000.0 * 100.0);
    }

    #[test]
    fn test_reset() {
        let mut mfi = MoneyFlowIndex::new(3).unwrap();

        let bar1 = Bar::new().high(2).low(1).close(1.5).volume(1000.0);
        let bar2 = Bar::new().high(5).low(3).close(4).volume(2000.0);
        let bar3 = Bar::new().high(9).low(7).close(8).volume(3000.0);
        let bar4 = Bar::new().high(5).low(3).close(4).volume(4000.0);
        let bar5 = Bar::new().high(5).low(3).close(4).volume(5000.0);
        let bar6 = Bar::new().high(2).low(1).close(1.5).volume(6000.0);

        assert_eq!(mfi.next(&bar1), 50.0);
        assert_eq!(mfi.next(&bar2), 100.0);
        assert_eq!(mfi.next(&bar3), 100.0);
        assert_eq!(round(mfi.next(&bar4)), 66.667);
        assert_eq!(round(mfi.next(&bar5)), 73.333);
        assert_eq!(round(mfi.next(&bar6)), 44.444);

        mfi.reset();

        assert_eq!(mfi.next(&bar1), 50.0);
        assert_eq!(mfi.next(&bar2), 100.0);
        assert_eq!(mfi.next(&bar3), 100.0);
        assert_eq!(round(mfi.next(&bar4)), 66.667);
        assert_eq!(round(mfi.next(&bar5)), 73.333);
        assert_eq!(round(mfi.next(&bar6)), 44.444);
    }

    #[test]
    fn test_default() {
        MoneyFlowIndex::default();
    }

    #[test]
    fn test_display() {
        let mfi = MoneyFlowIndex::new(10).unwrap();
        assert_eq!(format!("{}", mfi), "MFI(10)");
    }

}