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   10449 use strict;
  5         9  
  5         227  
4 5     5   25 use warnings;
  5         12  
  5         120  
5 5     5   22 use Carp;
  5         7  
  5         2294  
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 1500 my $class = shift;
15 17         76 my $this = bless {
16             EMA => undef,
17             R => 0,
18             R1 => 0,
19             }, $class;
20              
21 17         25 my $days = shift;
22 17 100       49 if( defined $days ) {
23 2         6 $this->set_days( $days );
24             }
25              
26 17         88 return $this;
27             }
28              
29             sub set_days {
30 17     17 0 31 my $this = shift;
31 17         34 my $arg = int(shift);
32              
33 17 50       44 croak "days must be a positive non-zero integer" if $arg <= 0;
34              
35 17         75 $this->{R} = 2.0 / (1.0 + $arg);
36 17         38 $this->{R1} = (1 - $this->{R});
37 17         36 $this->{days} = $arg;
38              
39 17         70 $this->{tag} = "EMA($this->{days})";
40             }
41              
42             sub insert {
43 6614     6614 0 8055 my $this = shift;
44              
45 6614 50       13761 croak "You must set the number of days before you try to insert" if not $this->{R};
46              
47 6614         14045 while( defined(my $Yt = shift) ) {
48 6619 100       12206 if( defined(my $e = $this->{EMA}) ) {
49 6406         31563 $this->{EMA} = ( $this->{R} * $Yt ) + ( $this->{R1} * $e );
50              
51             } else {
52 213         216 my ($p,$N);
53 213 100 100     992 if( ref($p = $this->{_p}) and (($N = @$p) >= $this->{days}-1) ) {
54 15         34 my $sum = 0;
55 15         109 $sum += $_ for @$p;
56              
57 15         55 $this->{EMA} = ( $this->{R} * $Yt ) + ( $this->{R1} * ($sum/$N) );
58 15         90 delete $this->{_p};
59              
60             } else {
61 198         205 push @{$this->{_p}}, $Yt;
  198         946  
62             }
63             }
64             }
65             }
66              
67             sub query {
68 6537     6537 0 8256 my $this = shift;
69              
70 6537         19140 return $this->{EMA};
71             }
72              
73             __END__