| 1 | # Copyright 2008, 2009, 2011 Kevin Ryde | ||
| 2 | |||
| 3 | # This file is part of Chart. | ||
| 4 | # | ||
| 5 | # Chart is free software; you can redistribute it and/or modify it under the | ||
| 6 | # terms of the GNU General Public License as published by the Free Software | ||
| 7 | # Foundation; either version 3, or (at your option) any later version. | ||
| 8 | # | ||
| 9 | # Chart is distributed in the hope that it will be useful, but WITHOUT ANY | ||
| 10 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS | ||
| 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more | ||
| 12 | # details. | ||
| 13 | # | ||
| 14 | # You should have received a copy of the GNU General Public License along | ||
| 15 | # with Chart. If not, see <http://www.gnu.org/licenses/>. | ||
| 16 | |||
| 17 | package App::Chart::Series::Derived::Momentum; | ||
| 18 | use 5.010; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use Carp; | ||
| 22 | use Locale::TextDomain ('App-Chart'); | ||
| 23 | |||
| 24 | use base 'App::Chart::Series::Indicator'; | ||
| 25 | use App::Chart::Series::Derived::SMA; | ||
| 26 | |||
| 27 | |||
| 28 | sub longname { __('Momentum') } | ||
| 29 | *shortname = \&longname; | ||
| 30 | sub manual { __p('manual-node','Momentum and Rate of Change') } | ||
| 31 | |||
| 32 | use constant | ||
| 33 | { type => 'indicator', | ||
| 34 | units => 'price', | ||
| 35 | hlines => [ 0 ], | ||
| 36 | parameter_info => [ { name => __('Days'), | ||
| 37 | key => 'momentum_days', | ||
| 38 | type => 'integer', | ||
| 39 | minimum => 1, | ||
| 40 | default => 40 } ], | ||
| 41 | }; | ||
| 42 | |||
| 43 | sub new { | ||
| 44 | my ($class, $parent, $N) = @_; | ||
| 45 | |||
| 46 | return $class->SUPER::new | ||
| 47 | (parent => $parent, | ||
| 48 | N => $N, | ||
| 49 | parameters => [ $N ], | ||
| 50 | arrays => { values => [] }); | ||
| 51 | } | ||
| 52 | *warmup_count = \&App::Chart::Series::Derived::SMA::warmup_count; # $N-1 | ||
| 53 | |||
| 54 | sub proc { | ||
| 55 | my ($self_or_class, $N) = @_; | ||
| 56 | |||
| 57 | # $a[0] is the newest point, $a[1] the prev, through to $a[$N-1] | ||
| 58 | my @a; | ||
| 59 | my $pos = $N-1; # initial pre-extends | ||
| 60 | |||
| 61 | return sub { | ||
| 62 | my ($value) = @_; | ||
| 63 | my $prev = $a[$pos]; | ||
| 64 | $a[$pos] = $value; | ||
| 65 | if (++$pos >= $N) { $pos = 0; } | ||
| 66 | |||
| 67 | if (defined $prev) { | ||
| 68 | return $value - $prev; | ||
| 69 | } else { | ||
| 70 | return undef; | ||
| 71 | } | ||
| 72 | }; | ||
| 73 | } | ||
| 74 | |||
| 75 | 1; | ||
| 76 | __END__ |