App/Chart/Latest.pm untested

filter: Statementstmt 0.0% 0 / 153 Branchbran 0.0% 0 / 42 Conditioncond 0.0% 0 / 44 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 305 CC 22 SCAR 33.2
CC
22
Cov
0%
get
72.0
form_short_datetime
56.0
formatted_volume
42.0
CRAP 27.6
1 # Copyright 2007, 2008, 2009, 2010, 2011, 2014, 2015, 2016, 2017 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::Latest;
18 use 5.006;
19 use strict;
20 use warnings;
21 use Date::Calc;
22 use Encode;
23 use List::Util qw(min max);
24 use POSIX ();
25 use Locale::TextDomain ('App-Chart');
26  
27 use App::Chart;
28 use App::Chart::LatestHandler;
29 use App::Chart::TZ;
30 use App::Chart::Timebase;
31  
32 # uncomment this to run the ### lines
33 # use Smart::Comments;
34  
35 our %get_cache = ();
36  
37 sub _purge_cache_on_latest_changed {
38 my ($symbol_hash) = @_;
39 ### _purge_cache_on_latest_changed(): join (', ', grep {exists $get_cache{$_}} keys %$symbol_hash)
40  
41 delete @get_cache{keys %$symbol_hash}; # hash slice
42 }
43  
44 sub get {
45 my ($class,$symbol) = @_;
46 ### Latest: $symbol
47  
48 if (! tied %get_cache) {
49 require Tie::Cache;
50 tie %get_cache, 'Tie::Cache', { MaxCount => 100 };
51 App::Chart::chart_dirbroadcast()->connect_first
52 ('latest-changed', \&_purge_cache_on_latest_changed);
53 }
54 if (my $latest = $get_cache{$symbol}) {
55 ### cached: $latest
56 return $latest;
57 }
58  
59 require App::Chart::DBI;
60 my $dbh = App::Chart::DBI->instance;
61 my $latest = do {
62 my $sth = $dbh->prepare_cached
63 ('SELECT symbol, name, currency,
64 quote_date, quote_time, bid, offer,
65 last_date, last_time, open, high, low, last, change, volume,
66 source, halt, limit_up, limit_down,
67 dividend, note, error, fetch_timestamp
68 FROM latest
69 WHERE symbol=?');
70 $dbh->selectrow_hashref ($sth, undef, $symbol);
71 };
72 ### FROM latest: $latest
73  
74 if (! defined $latest) {
75 my $sth = $dbh->prepare_cached
76 ('SELECT symbol, date, open, high, low, close, volume
77 FROM daily WHERE symbol=? AND close NOT NULL
78 ORDER BY date DESC LIMIT 2');
79 my $aref = $dbh->selectall_arrayref ($sth, { Slice => {} }, $symbol);
80 $latest = $aref->[0];
81 my $prev = $aref->[1];
82 if (defined ($latest)) {
83 $latest->{'last_date'} = delete $latest->{'date'};
84 my $last = $latest->{'last'} = delete $latest->{'close'};
85 $latest->{'source'} = 'database';
86  
87 if (defined $last && defined(my $prev_close = $prev->{'close'})) {
88 $latest->{'change'} = App::Chart::decimal_sub ($last, $prev_close);
89 }
90  
91 my $info_get_sth = $dbh->prepare_cached
92 ('SELECT name, currency, exchange FROM info WHERE symbol=?');
93 ($latest->{'name'}, $latest->{'currency'}, $latest->{'exchange'})
94 = $dbh->selectrow_array ($info_get_sth, undef, $symbol);
95 }
96 ### FROM daily: $latest
97 }
98  
99 # if the latest record doesn't already have a dividend then check the database
100 # (and always do so when constructing from daily data)
101 if (defined $latest && defined $latest->{'last_date'}) {
102 $latest->{'dividend'} //= App::Chart::DBI->read_single
103 ('SELECT amount FROM dividend WHERE symbol=? AND ex_date=?',
104 $symbol, $latest->{'last_date'});
105 }
106  
107 if (! defined ($latest)) {
108 $latest = { symbol => $symbol,
109 error => __('no data'),
110 source => 'dummy' };
111 ### fallback no data: $latest
112 }
113  
114 # $latest->{'inprogress'} = ($App::Chart::Gtk2::Job::Latest::inprogress{$symbol}
115 # ? 1 : 0);
116  
117 $get_cache{$symbol} = $latest;
118 return bless $latest, $class;
119 }
120  
121 sub quote_adate {
122 my ($self) = @_;
123 my $iso = $self->{'quote_date'};
124 if (! defined $iso) { return undef; }
125 return iso_to_adate ($iso);
126 }
127  
128 sub last_adate {
129 my ($self) = @_;
130 my $iso = $self->{'last_date'};
131 if (! defined $iso) { return undef; }
132 return iso_to_adate ($iso);
133 }
134  
135 sub iso_to_adate {
136 my ($iso) = @_;
137 my ($year, $month, $day) = App::Chart::iso_to_ymd ($iso);
138 return App::Chart::ymd_to_adate ($year, $month, $day);
139 }
140  
141 sub short_datetime {
142 my ($self) = @_;
143 return ($self->{'short_datetime'} ||= do {
144 my $isodate = $self->{'quote_date'};
145 my $timestr = $self->{'quote_time'};
146  
147 # if there's a quote date but no bid/offer, then use last-date, but only
148 # if there's an actual value for last-date
149 if ((! defined $isodate || (! $self->{'bid'} && ! $self->{'offer'}))
150 && defined $self->{'last_date'}) {
151 $isodate = $self->{'last_date'};
152 $timestr = $self->{'last_time'};
153 }
154 form_short_datetime ($self->{'symbol'}, $isodate, $timestr)
155 });
156 }
157  
158  
159 sub hmsstr_to_seconds {
160 my ($str) = @_;
161 my ($hour, $min, $sec) = split /:/, $str;
162 return App::Chart::hms_to_seconds ($hour, $min, $sec||0);
163 }
164  
165 sub mjd_to_week {
166 my ($mjd) = @_;
167 return int (($mjd+2) / 7);
168 }
169  
170 # $show_iso is an ISO date string like '2008-08-20'
171 # $show_timestr is a time string like '14:59:59'
172 # both are in the timezone of $symbol
173 # return a short string representing the date and/or time
174 #
175 sub form_short_datetime {
176 my ($symbol, $show_iso, $show_timestr) = @_;
177 if (! defined $show_iso) { return ''; }
178  
179 my $timezone = App::Chart::TZ->for_symbol ($symbol);
180 my ($now_year, $now_month, $now_day) = $timezone->ymd;
181 my $now_iso = App::Chart::ymd_to_iso ($now_year, $now_month, $now_day);
182  
183 if ($now_iso eq $show_iso) {
184 if (defined $show_timestr) {
185 $show_timestr =~ s/:[0-9]+$//; # lose trailing seconds
186 return $show_timestr;
187 } else {
188 return __('Today');
189 }
190 }
191  
192 my ($show_year, $show_month, $show_day) = App::Chart::iso_to_ymd ($show_iso);
193  
194 my $now_days = Date::Calc::Date_to_Days ($now_year, $now_month, $now_day);
195 my $show_days = Date::Calc::Date_to_Days ($show_year,$show_month,$show_day);
196  
197 # 1=Mon, 2=Tue, ...
198 my $now_dow = Date::Calc::Day_of_Week ($now_year, $now_month, $now_day);
199 my $show_dow = Date::Calc::Day_of_Week ($show_year, $show_month, $show_day);
200  
201 my $now_wdate = $now_days - $now_dow;
202 my $show_wdate = $show_days - $show_dow;
203  
204 # default full date
205 my $format = '%d%b%Y';
206  
207 if ($now_wdate == $show_wdate
208 || ($now_wdate == $show_wdate + 1
209 && (($now_dow == 1 || $now_dow == 2) # Mon or Tue
210 && $now_days - $show_days <= 4))) {
211 # for same week, or on Mon the prev Thu,Fri or on Tue the prev Fri, just
212 # show day
213 $format = '%a';
214  
215 } elsif ($show_year == $now_year
216 || ($show_year + 1 == $now_year
217 && $show_month == 12 && $now_month == 1)) {
218 # for this year, or for Dec in Jan, just show mday+month
219 $format = '%d-%b';
220  
221 } elsif (abs ($show_year - $now_year) < 40) {
222 # for +/- 40 years of today, show abbreviated year
223 $format = '%d%b%y';
224 }
225  
226 return App::Chart::Timebase::strftime_ymd
227 ($format, $show_year, $show_month, $show_day);
228 }
229  
230 sub mjd_to_weeknum {
231 my ($mjd) = @_;
232 return POSIX::floor ((POSIX::floor($mjd) - 2) / 7);
233 }
234  
235 sub formatted_volume {
236 my ($latest) = @_;
237 my $volume = $latest->{'volume'};
238 if (! defined $volume) { return undef; }
239 if (my $fv = $latest->{'formatted_volume'}) { return $fv; }
240  
241 my $suffix = '';
242 if ($volume >= 10_000_000_000) {
243 # billions
244 $volume /= 1_000_000_000;
245 $suffix = __p('billions','b');
246 } elsif ($volume >= 10_000_000) {
247 # millions
248 $volume /= 1_000_000;
249 $suffix = __p('millions','m');
250 } elsif ($volume >= 10_000) {
251 # millions
252 $volume /= 1_000;
253 $suffix = __p('thousands','k');
254 }
255 my $decimals = max (0, 3 - num_integer_digits ($volume));
256 my $nf = App::Chart::number_formatter();
257 return ($latest->{'formatted_volume'}
258 = $nf->format_number ($volume, $decimals, 0) . $suffix);
259 }
260  
261 sub num_integer_digits {
262 my ($n) = @_;
263 return 1 + max (0, POSIX::floor (POSIX::log10 (abs ($n))));
264 }
265  
266 1;
267 __END__