File Coverage

blib/lib/Math/Business/EMA.pm
Criterion Covered Total %
statement 37 39 94.8
branch 8 10 80.0
condition 3 3 100.0
subroutine 7 9 77.7
pod 0 6 0.0
total 55 67 82.0


line stmt bran cond sub pod time code
1             package Math::Business::EMA;
2              
3 5     5   8317 use strict;
  5         22  
  5         130  
4 5     5   22 use warnings;
  5         6  
  5         119  
5 5     5   19 use Carp;
  5         11  
  5         1960  
6              
7             1;
8              
9 0     0 0 0 sub tag { (shift)->{tag} }
10              
11 0     0 0 0 sub recommended { croak "no recommendation" }
12              
13             sub new {
14 17     17 0 356 my $class = shift;
15 17         49 my $this = bless {
16             EMA => undef,
17             R => 0,
18             R1 => 0,
19             }, $class;
20              
21 17         23 my $days = shift;
22 17 100       34 if( defined $days ) {
23 2         5 $this->set_days( $days );
24             }
25              
26 17         70 return $this;
27             }
28              
29             sub set_days {
30 17     17 0 20 my $this = shift;
31 17         20 my $arg = int(shift);
32              
33 17 50       32 croak "days must be a positive non-zero integer" if $arg <= 0;
34              
35 17         49 $this->{R} = 2.0 / (1.0 + $arg);
36 17         29 $this->{R1} = (1 - $this->{R});
37 17         26 $this->{days} = $arg;
38              
39 17         47 $this->{tag} = "EMA($this->{days})";
40             }
41              
42             sub insert {
43 6614     6614 0 7110 my $this = shift;
44              
45 6614 50       9703 croak "You must set the number of days before you try to insert" if not $this->{R};
46              
47 6614         10083 while( defined(my $Yt = shift) ) {
48 6619 100       9179 if( defined(my $e = $this->{EMA}) ) {
49 6406         14971 $this->{EMA} = ( $this->{R} * $Yt ) + ( $this->{R1} * $e );
50              
51             } else {
52 213         254 my ($p,$N);
53 213 100 100     651 if( ref($p = $this->{_p}) and (($N = @$p) >= $this->{days}-1) ) {
54 15         22 my $sum = 0;
55 15         56 $sum += $_ for @$p;
56              
57 15         36 $this->{EMA} = ( $this->{R} * $Yt ) + ( $this->{R1} * ($sum/$N) );
58 15         69 delete $this->{_p};
59              
60             } else {
61 198         234 push @{$this->{_p}}, $Yt;
  198         616  
62             }
63             }
64             }
65             }
66              
67             sub query {
68 6537     6537 0 6954 my $this = shift;
69              
70 6537         11145 return $this->{EMA};
71             }
72              
73             __END__