| 1 | # Copyright 2008, 2009, 2010 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::SMA; | ||
| 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 | |||
| 26 | # uncomment this to run the ### lines | ||
| 27 | #use Smart::Comments; | ||
| 28 | |||
| 29 | |||
| 30 | sub longname { __('SMA - Simple MA') } | ||
| 31 | sub shortname { __('SMA') } | ||
| 32 | sub manual { __p('manual-node','Simple Moving Average') } | ||
| 33 | |||
| 34 | use constant | ||
| 35 | { priority => 13, | ||
| 36 | type => 'average', | ||
| 37 | parameter_info => [ { name => __('Days'), | ||
| 38 | key => 'sma_days', | ||
| 39 | type => 'integer', | ||
| 40 | minimum => 1, | ||
| 41 | default => 20 } ], | ||
| 42 | }; | ||
| 43 | |||
| 44 | sub new { | ||
| 45 | my ($class, $parent, $N) = @_; | ||
| 46 | ### SMA new: \@_ | ||
| 47 | |||
| 48 | $N //= parameter_info()->[0]->{'default'}; | ||
| 49 | ($N > 0) || croak "SMA bad N: $N"; | ||
| 50 | |||
| 51 | return $class->SUPER::new | ||
| 52 | (parent => $parent, | ||
| 53 | parameters => [ $N ], | ||
| 54 | arrays => { values => [] }, | ||
| 55 | array_aliases => { }); | ||
| 56 | } | ||
| 57 | sub warmup_count { | ||
| 58 | my ($self_or_class, $N) = @_; | ||
| 59 | return $N - 1; | ||
| 60 | } | ||
| 61 | sub proc { | ||
| 62 | my ($class_or_self, $N) = @_; | ||
| 63 | |||
| 64 | if ($N <= 1) { | ||
| 65 | return \&App::Chart::Series::Calculation::identity; | ||
| 66 | } | ||
| 67 | |||
| 68 | my @array; | ||
| 69 | my $pos = $N - 1; # initial extends | ||
| 70 | my $total = 0; | ||
| 71 | my $count = 0; | ||
| 72 | return sub { | ||
| 73 | my ($value) = @_; | ||
| 74 | |||
| 75 | # drop old | ||
| 76 | if ($count >= $N) { | ||
| 77 | $total -= $array[$pos]; | ||
| 78 | } else { | ||
| 79 | $count++; | ||
| 80 | } | ||
| 81 | |||
| 82 | # add new | ||
| 83 | $total += ($array[$pos] = $value); | ||
| 84 | if (++$pos >= $N) { $pos = 0; } | ||
| 85 | |||
| 86 | return $total / $count; | ||
| 87 | }; | ||
| 88 | } | ||
| 89 | |||
| 90 | 1; | ||
| 91 | __END__ |