App/Chart/Series/Derived/Median.pm untested

filter: Statementstmt 0.0% 0 / 59 Branchbran 0.0% 0 / 2 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 89 CC 2 SCAR 9.2
CC
2
Cov
0%
proc
6.0
longname
2.0
shortname
2.0
CRAP 2.5
1 # Copyright 2008, 2009, 2011, 2012 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::Median;
18 use 5.010;
19 use strict;
20 use warnings;
21 use Carp;
22 use List::Util qw(min max);
23 use POSIX ();
24 use Locale::TextDomain ('App-Chart');
25  
26 use base 'App::Chart::Series::Indicator';
27 use App::Chart::Series::Derived::SMA;
28  
29  
30 sub longname { __('Moving Median') }
31 sub shortname { __('Median') }
32 sub manual { __p('manual-node','Moving Median') }
33  
34 use constant
35 { type => 'average',
36 priority => -10,
37 parameter_info => [ { name => __('Days'),
38 key => 'median_days',
39 type => 'integer',
40 minimum => 1,
41 default => 20 } ],
42 };
43  
44 sub new {
45 my ($class, $parent, $N) = @_;
46  
47 $N //= parameter_info()->[0]->{'default'};
48 ($N > 0) || croak "Median bad N: $N";
49  
50 return $class->SUPER::new
51 (parent => $parent,
52 N => $N,
53 parameters => [ $N ],
54 arrays => { values => [] },
55 array_aliases => { });
56 }
57 *warmup_count = \&App::Chart::Series::Derived::SMA::warmup_count; # $N-1
58  
59 sub proc {
60 my ($class_or_self, $N) = @_;
61 $N = max ($N, 1);
62  
63 my @array;
64 my @sorted;
65 my $mid1 = 0;
66 my $mid2 = 0;
67 return sub {
68 my ($value) = @_;
69  
70 # add new
71 unshift @array, $value;
72  
73 # drop old
74 if (@array > $N) {
75 pop @array;
76 } else {
77 # odd elems eg. 5 indexes 0,1,2,3,4 gives mid1==mid2==2 (N-1)/2
78 # even elems eg. 4 indexes 0,1,2,3 gives mid1==1,mid2==2 f/c of (N-1)/2
79 $mid1 = POSIX::floor ((@array - 1) / 2);
80 $mid2 = POSIX::ceil ((@array - 1) / 2);
81 }
82  
83 @sorted = sort {$a<=>$b} @array;
84 return ($sorted[$mid1] + $sorted[$mid2]) / 2;
85 };
86 }
87  
88 1;
89 __END__