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

filter: Statementstmt 0.0% 0 / 98 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 142 CC 5 SCAR 17.0
CC
5
Cov
0%
proc
20.0
yfactor
6.0
longname
2.0
CRAP 5.5
1 # Copyright 2007, 2009, 2010, 2011, 2024 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::RSquared;
18 use 5.010;
19 use strict;
20 use warnings;
21 use Carp;
22 use List::Util qw(min max);
23 use Locale::TextDomain ('App-Chart');
24  
25 use base 'App::Chart::Series::Indicator';
26 use App::Chart::Series::Derived::SMA;
27  
28 use constant DEBUG => 0;
29  
30  
31 # http://www.traderslog.com/r-squared.htm
32 # Sample Coors (NYSE symbol "TAP") from Feb 2002 (the year isn't shown,
33 # but is 2002).
34 #
35 # http://mathworld.wolfram.com/CorrelationCoefficient.html
36 # Explanation of general case, incl formulas.
37 #
38  
39  
40 sub longname { __('R-Squared Index') }
41 sub shortname { __('R-Squared') }
42 sub manual { __p('manual-node','R-Squared Index') }
43  
44 use constant
45 { type => 'indicator',
46 units => 'zero_to_one',
47 minimum => 0,
48 maximum => 1,
49 parameter_info => [ { name => __('Days'),
50 key => 'rsquared_days',
51 type => 'integer',
52 minimum => 1,
53 default => 14 } ],
54 };
55  
56 sub new {
57 my ($class, $parent, $N) = @_;
58  
59 $N //= parameter_info()->[0]->{'default'};
60 ($N > 0) || croak "RSquared bad N: $N";
61  
62 return $class->SUPER::new
63 (parent => $parent,
64 N => $N,
65 parameters => [ $N ],
66 arrays => { values => [] },
67 array_aliases => { });
68 }
69 *warmup_count = \&App::Chart::Series::Derived::SMA::warmup_count; # $N-1
70  
71 # Return the factor for r-squared arising from the denominator Y variance.
72 # This is
73 #
74 # 1
75 # -------------------------------------------------
76 # n * (1^2 + 2^2 + ... + n^2) - (1 + 2 + ... + n)^2
77 #
78 # and the denominator here is (n^4 - n^2)/12, per the DEBUG code below.
79 #
80 sub yfactor {
81 my ($N) = @_;
82 if ($N < 2) { return 1; }
83 return 12.0 / ($N*$N * ($N*$N - 1));
84 }
85 if (DEBUG) {
86 my $triangle = sub {
87 my ($n) = @_;
88 return List::Util::sum (1 .. $n);
89 };
90 my $sum_squares = sub {
91 my ($n) = @_;
92 return List::Util::sum (map {$_**2} (1 .. $n));
93 };
94 my $yden = sub {
95 my ($n) = @_;
96 return $n * $sum_squares->($n) - ($triangle->($n))**2;
97 };
98 require Math::Polynomial;
99 require Math::BigRat;
100 Math::Polynomial->verbose(1);
101 Math::Polynomial->configure(VARIABLE => "\$N");
102 my $poly = Math::Polynomial::interpolate (map {
103 ($_, Math::BigRat->new(12 * $yden->($_)))} (1..10));
104 print "yfactor 1/12 * ($poly)\n";
105 }
106  
107 # return the triangular number of N, ie. N*(N+1)/2
108 sub triangular {
109 my ($n) = @_;
110 return $n * ($n+1) / 2;
111 }
112  
113 sub proc {
114 my ($class, $N) = @_;
115  
116 # This is the correlation coefficient of the last COUNT many X values,
117 # against a set of Y values 1, 2, 3, ..., COUNT. Or fewer than COUNT
118 # until that many values have been seen. The formula in the manual is
119 #
120 # (Covariance X,Y)^2
121 # r^2 = ---------------------------
122 # (Variance X) * (Variance Y)
123 #
124 # which is
125 #
126 # (Sum X*Y)/N - (Sum X)/N * (Sum Y)/N
127 # r^2 = -------------------------------------------------------------
128 # ((Sum X^2)/N - (Sum X)^2/N^2) * ((Sum Y^2)/N - (Sum Y)^2/N^2)
129 #
130 # But in the code a factor of N^2 is put through numerator and
131 # denominator to give
132 #
133 # N * Sum X*Y - Sum X * Sum Y
134 # r^2 = -----------------------------------------------------
135 # (N * Sum X^2 - (Sum X)^2) * (N * Sum Y^2 - (Sum Y)^2)
136 #
137 # In the degenerate case N==1, the variance of the Y values is 0, so
138 # r^2=0/0. Return 1 in that case, considering a single value is perfectly
139 # correlated.
140 #
141 # If all the X values are the same then r^2 = 0/0. Return 1 in that case,
142 # because those X values are a perfect straight line, a horizontal one.
143 #
144 #
145 # @array,$pos is a circular list of the last $N many X values.
146 #
147 # $count is the number of values in @array.
148 #
149 # $x_total is the sum of the values in @array.
150 #
151 # $xx_total is the sum of the squares of the values in @array.
152 #
153 # $y_total is the sum of the Y values corresponding to the values in
154 # @array, which means 1+2+...+$count, which is a triangular number. This
155 # varies until $count==$N is reached and is then a constant.
156 #
157 # $y_factor is the variance factor in the denominator, see yfactor()
158 # above. This varies until $count==$N is reached and is then a constant.
159 #
160 # $xy_total is the sum of the product x*y for each x,y pair, which means
161 # x[1]*1 + x[2]*2 + ... + x[POINTS]*POINTS. When shifting out an old X,
162 # the weighting of each x in the sum is reduced by subtracting X-TOTAL.
163 #
164  
165 my @array;
166 my $pos = $N - 1; # initial extends
167 my $x_total = 0;
168 my $xx_total = 0;
169 my $y_total = 0;
170 my $y_factor = 0;
171 my $xy_total = 0;
172  
173 my $count = 0;
174 return sub {
175 my ($x) = @_;
176  
177 if ($count >= $N) {
178 # drop oldest point
179 my $prev_x = $array[$pos];
180 $xy_total -= $x_total;
181 $x_total -= $prev_x;
182 $xx_total -= $prev_x ** 2;
183 } else {
184 # gaining a point
185 $count++;
186 $y_factor = yfactor($count);
187 $y_total = triangular($count);
188 }
189 $array[$pos] = $x;
190 if (++$pos >= $N) { $pos = 0; }
191  
192 # add this point
193 $x_total += $x;
194 $xx_total += $x*$x;
195 $xy_total += $x * $count;
196  
197 my $den = $xx_total*$count - $x_total*$x_total;
198 if ($den == 0) { return 1; }
199  
200 return $y_factor * ($xy_total*$count - $x_total*$y_total)**2 / $den;
201 };
202 }
203  
204 1;
205 __END__