App/Chart/Download.pm

filter: Statementstmt 94.2% 33 / 35 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 12 / 12 Podpod n/a totaltotal 95.7% 45 / 47 CC 1 SCAR 0.2
CC
1
Cov
94%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« App/Chart/Barchart.pm ↑ Summary App/Chart/DownloadHandler.pm »
1 # Download functions.
2  
3 # Copyright 2007, 2008, 2009, 2010, 2011, 2013, 2015, 2016, 2017, 2018, 2020 Kevin Ryde
4  
5 # This file is part of Chart.
6 #
7 # Chart is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3, or (at your option) any later version.
10 #
11 # Chart is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 # details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Chart. If not, see <http://www.gnu.org/licenses/>.
18  
19 package App::Chart::Download;
20 2 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 2 ▶use Carp 'carp','croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
24 2 ▶use Date::Calc;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 2 ▶use List::Util qw(min max);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 2 ▶use List::MoreUtils;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 2 ▶use Regexp::Common 'whitespace';
Subroutine BEGIN: called CC=1 SCAR=0.0
28 2 ▶use Locale::TextDomain ('App-Chart');
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 2 ▶use PerlIO::via::EscStatus;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 2 ▶use Tie::TZ;
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 2 ▶use App::Chart;
Subroutine BEGIN: called CC=1 SCAR=2.6
34 use App::Chart::Database;
35 use App::Chart::DBI;
36 use App::Chart::TZ;
37  
38 # uncomment this to run the ### lines
39 # use Smart::Comments;
40  
41 use constant DEBUG => 0;
42  
43 #------------------------------------------------------------------------------
44  
45 sub get {
46 my ($class, $url, %options) = @_;
47 ### Download get(): $url
48  
49 # URI object becomes string
50 $url = "$url";
51  
52 my $ua = $options{'ua'} || do { require App::Chart::UserAgent;
53 App::Chart::UserAgent->instance };
54 $ua->cookie_jar ($options{'cookie_jar'}); # undef for none
55  
56 require HTTP::Request;
57 my $method = $options{'method'} || 'GET';
58 my @headers = (Referer => $options{'referer'});
59 my $data = $options{'data'};
60 if (defined $data) {
61 push @headers, 'Content-Type' => 'application/x-www-form-urlencoded';
62 }
63 my $req = HTTP::Request->new ($method, $url, \@headers, $data);
64  
65 # possible override
66 if (my $user_agent = $options{'user_agent'}) {
67 $req->user_agent($user_agent);
68 }
69  
70 my $etag = $options{'etag'};
71 my $lastmod = $options{'last_modified'};
72  
73 if (my $key = $options{'url_tags_key'}) {
74 my $symbol = $options{'symbol'};
75 my $prev_url = App::Chart::Database->read_extra($symbol,"$key-URL");
76 if (defined $prev_url && $url eq $prev_url) {
77 $etag = App::Chart::Database->read_extra($symbol,"$key-ETag");
78 $lastmod = App::Chart::Database->read_extra($symbol,"$key-Last-Modified");
79 }
80 }
81  
82 if ($etag) { $req->header ('If-None-Match' => $etag); }
83 if ($lastmod) { $req->header ('If-Modified-Since' => $lastmod); }
84  
85 $ua->prepare_request ($req);
86 if (DEBUG) { print $req->as_string; }
87  
88 if ($App::Chart::option{'verbose'} || DEBUG) {
89 if ($App::Chart::option{'verbose'} >= 2 || DEBUG >= 2) {
90 print $req->as_string;
91 } else {
92 print "$method $url\n";
93 }
94 if (defined $data) {
95 print "$data\n";
96 }
97 }
98  
99 my $resp = $ua->request ($req);
100 if (DEBUG) { print $resp->status_line,"\n";
101 print $resp->headers->as_string,"\n"; }
102  
103 # internal message from LWP when a keep-alive has missed the boat
104 if ($resp->status_line =~ /500 Server closed connection/i) {
105 substatus (__('retry'));
106 $resp = $ua->request ($req);
107 if (DEBUG) { print $resp->status_line,"\n";
108 print $resp->headers->as_string,"\n"; }
109 }
110  
111 if ($resp->is_success
112 || ($options{'allow_401'} && $resp->code == 401)
113 || ($options{'allow_404'} && $resp->code == 404)
114 || (($etag || $lastmod) && $resp->code == 304)) {
115 substatus (__('processing'));
116 return $resp;
117 } else {
118 croak "Cannot download $url\n",$resp->status_line,"\n";
119 }
120 }
121  
122 #------------------------------------------------------------------------------
123  
124 my $last_status = ''; # without substatus addition
125  
126 sub download_message {
127 print join (' ',@_),"\n";
128 }
129 sub verbose_message {
130 if ($App::Chart::option{'verbose'}) {
131 print join (' ',@_),"\n";
132 }
133 }
134  
135 sub status {
136 my $str = join (' ', @_);
137 $last_status = $str;
138 PerlIO::via::EscStatus::print_status ($str);
139 }
140 sub substatus {
141 my ($str) = @_;
142 if ($str) {
143 PerlIO::via::EscStatus::print_status ($last_status, ' [', $str, ']');
144 }
145 }
146  
147 #------------------------------------------------------------------------------
148  
149 sub split_lines {
150 my ($str) = @_;
151 my @lines = split (/[\r\n]+/, $str); # LF or CRLF
152 foreach (@lines) { $_ =~ s/[ \t]+$// } # trailing whitespace
153 return grep {$_ ne ''} @lines; # no blanks
154 }
155  
156 #------------------------------------------------------------------------------
157  
158 sub trim_decimals {
159 my ($str, $want_decimals) = @_;
160 if ($str && $str =~ /(.*\.[0-9]{$want_decimals}[0-9]*?)0+$/) {
161 return $1;
162 } else {
163 return $str;
164 }
165 }
166  
167 #------------------------------------------------------------------------------
168  
169 sub str_is_zero {
170 my ($str) = @_;
171 return ($str =~ /^0+(\.0*)?$|^0*(\.0+)$/ ? 1 : 0);
172 }
173  
174  
175 #------------------------------------------------------------------------------
176  
177 sub cents_to_dollars {
178 my ($str) = @_;
179 $str =~ /^([^.]*)(\.(.*))?$/
180 or croak "cents_to_dollars(): bad string: \"$str\"";
181 my $int = $1;
182 my $frac = (defined $3 ? $3 : '');
183 if (length ($int) < 3) {
184 $int = sprintf ('%03s', $int);
185 }
186 return substr ($int, 0, length($int)-2) . '.' .
187 substr ($int, length($int)-2) . $frac;
188 }
189  
190  
191 #------------------------------------------------------------------------------
192  
193 sub month_to_nearest_year {
194 my ($target_month) = @_;
195 my ($year, $month, $day) = Date::Calc::Today();
196 $month --; # 0=January
197 $target_month --;
198  
199 my $diff = $target_month - $month;
200 $diff += 5;
201 $diff %= 12;
202 $diff -= 5; # now range -5 to +6
203  
204 # applying $diff makes $month == $target_month modulo 12,
205 # but $month<0 is last year, 0 to 11 this year, >= 12 next year
206 $month += $diff;
207 return $year + ($month < 0 ? -1 : $month < 12 ? 0 : 1);
208 }
209  
210  
211 #------------------------------------------------------------------------------
212  
213 sub Decode_Date_EU_to_iso {
214 my ($str, $noerror) = @_;
215 my ($year, $month, $day) = Date::Calc::Decode_Date_EU ($str);
216 unless (defined $year && defined $month && defined $day) {
217 if ($noerror) {
218 return undef;
219 } else {
220 croak "Decode_Date_EU_to_iso: unrecognised date \"$str\"\n";
221 }
222 }
223 return App::Chart::ymd_to_iso ($year, $month, $day);
224 }
225  
226 sub Decode_Date_US_to_iso {
227 my ($str) = @_;
228 my ($year, $month, $day) = Date::Calc::Decode_Date_US ($str);
229 unless (defined $year && defined $month && defined $day) {
230 croak "Decode_Date_US_to_iso: unrecognised date \"$str\"\n";
231 }
232 return App::Chart::ymd_to_iso ($year, $month, $day);
233 }
234  
235 #------------------------------------------------------------------------------
236  
237 sub Decode_Date_YMD {
238 my ($str) = @_;
239 ($str =~ m{^ # 6 or 8 digits are yyyymmdd or yymmdd
240 ["'[:space:]]*
241 (\d{2,4}) # $1 year
242 ((\d{2})|([A-Za-z]+)) # $3 numeric month, $4 alpha month
243 (\d{2}) # $5 day
244 ["'[:space:]]*
245 $}x)
246 or
247 ($str =~ m{^
248 ["'[:space:]]*
249 (\d{2,4}) # $1 year
250 [-_/:.[:space:]]*
251 ((\d{1,2})|([A-Za-z]+)) # $3 numeric month, $4 alpha month
252 [-_/:.[:space:]]*
253 (\d{1,2}) # $5 day
254 ["'[:space:]]*
255 $}x)
256 or return;
257  
258 my $year = $1;
259 my $num_month = $3;
260 my $alpha_month = $4,
261 my $day = $5;
262 my $month = $num_month || Date::Calc::Decode_Month ($alpha_month);
263 $year = Date::Calc::Moving_Window ($year);
264 return ($year, $month, $day);
265 }
266  
267 sub Decode_Date_YMD_to_iso {
268 my ($str) = @_;
269 my ($year, $month, $day) = Decode_Date_YMD ($str);
270 if (! defined $year || ! defined $month || ! defined $day
271 || ! Date::Calc::check_date ($year, $month, $day)) {
272 croak "Decode_Date_YMD_to_iso: invalid date \"$str\"\n";
273 }
274 return App::Chart::ymd_to_iso ($year, $month, $day);
275 }
276  
277  
278 #------------------------------------------------------------------------------
279  
280 sub date_parse_to_iso {
281 my ($str) = @_;
282 require Date::Parse;
283 my ($ss,$mm,$hh,$day,$month,$year,$zone) = Date::Parse::strptime ($str);
284 if (! defined ($day) || ! defined ($month) || ! defined ($year)) {
285 croak "date_parse_to_iso: unrecognised date \"$str\"\n";
286 }
287 return App::Chart::ymd_to_iso ($year + 1900, $month + 1, $day);
288 }
289  
290 #------------------------------------------------------------------------------
291  
292 # $h is a hash of share prices
293 # data => [ { symbol=>$str,
294 # date => $str,
295 # open => $price,
296 # high => $price,
297 # low => $price,
298 # close => $price,
299 # volume => $number,
300 # openint => $number,
301 # },
302 # ...
303 # ]
304 # dividends => [ { symbol => $str,
305 # ex_date => $date,
306 # record_date => $date,
307 # pay_date => $date,
308 # type => $str,
309 # amount => $price,
310 # imputation => $price,
311 # qualifier => $str,
312 # note => $str,
313 # },
314 # ...
315 # ],
316 # write it as daily data in the database
317 sub write_daily_group {
318 my ($h) = @_;
319  
320 crunch_h ($h);
321  
322 my $prefer_decimals = $h->{'prefer_decimals'};
323 my $database_symbols_hash = App::Chart::Database::database_symbols_hash();
324  
325 my %decimals;
326 my %data_changed;
327  
328 substatus (__('writing database'));
329 my $dbh = App::Chart::DBI->instance;
330 App::Chart::Database::call_with_transaction
331 ($dbh, sub {
332 if ($h->{'cost_key'}) {
333 require App::Chart::DownloadCost;
334 App::Chart::DownloadCost::cost_store_h ($h);
335 }
336  
337 my %symbol_hash;
338 {
339 my $sth = $dbh->prepare_cached
340 ('INSERT OR REPLACE INTO daily
341 (symbol, date, open, high, low, close, volume, openint)
342 VALUES (?,?,?,?,?,?,?,?)');
343  
344 foreach my $data (@{$h->{'data'}}) {
345 my $symbol = $data->{'symbol'};
346 next unless exists $database_symbols_hash->{$symbol};
347  
348 if (defined $prefer_decimals) {
349 $decimals{$symbol} = $prefer_decimals;
350 }
351 $data_changed{$symbol} = 1;
352  
353 $sth->execute($symbol,
354 $data->{'date'},
355 $data->{'open'},
356 $data->{'high'},
357 $data->{'low'},
358 $data->{'close'},
359 $data->{'volume'},
360 $data->{'openint'});
361 $sth->finish;
362 }
363 }
364  
365 foreach my $dividend (@{$h->{'dividends'}}) {
366 my $symbol = $dividend->{'symbol'}
367 or croak "write_daily_group: missing symbol in dividend record";
368 next unless exists $database_symbols_hash->{$symbol};
369  
370 my $ex_date = $dividend->{'ex_date'};
371 my $record_date = $dividend->{'record_date'};
372 my $pay_date = $dividend->{'pay_date'};
373  
374 my $type = $dividend->{'type'} || '';
375 my $amount = $dividend->{'amount'};
376 my $imputation = $dividend->{'imputation'};
377 my $qualifier = crunch_empty_undef ($dividend->{'qualifier'});
378 my $note = crunch_empty_undef ($dividend->{'note'});
379  
380 my $old_qualifier = App::Chart::DBI->read_single
381 ('SELECT qualifier FROM dividend WHERE symbol=? AND ex_date=? AND type=?', $symbol, $ex_date, $type);
382  
383 my $sth = $dbh->prepare_cached
384 ('INSERT OR REPLACE INTO dividend
385 (symbol, ex_date, record_date, pay_date,
386 type, amount, imputation, qualifier, note)
387 VALUES (?,?,?,?, ?,?,?,?,?)');
388  
389 $sth->execute ($symbol, $ex_date, $record_date, $pay_date,
390 $type, $amount, $imputation, $qualifier, $note);
391 $sth->finish;
392 $data_changed{$symbol} = 1;
393 }
394  
395 foreach my $split (@{$h->{'splits'}}) {
396 my $symbol = $split->{'symbol'}
397 or croak "write_daily_group: missing symbol in split record";
398 next unless exists $database_symbols_hash->{$symbol};
399  
400 my $date = $split->{'date'};
401 my $new = crunch_number ($split->{'new'});
402 my $old = crunch_number ($split->{'old'});
403 my $note = crunch_empty_undef ($split->{'note'});
404  
405 my $sth = $dbh->prepare_cached
406 ('INSERT OR REPLACE INTO split (symbol, date, new, old, note)
407 VALUES (?,?,?,?,?)');
408 $sth->execute ($symbol, $date, $new, $old, $note);
409 $sth->finish;
410 $data_changed{$symbol} = 1;
411 }
412  
413 if (my $names = $h->{'names'}) {
414 while (my ($symbol, $name) = each %$names) {
415 if (defined $name) {
416 $data_changed{$symbol} |= set_symbol_name ($symbol, $name);
417 }
418 }
419 }
420 if (my $currencies = $h->{'currencies'}) {
421 while (my ($symbol, $currency) = each %$currencies) {
422 if (defined $currency) {
423 $data_changed{$symbol} |= set_currency ($symbol, $currency);
424 }
425 }
426 }
427 if (my $isins = $h->{'isins'}) {
428 while (my ($symbol, $isin) = each %$isins) {
429 if (defined $isin) {
430 $data_changed{$symbol} |= set_isin ($symbol, $isin);
431 }
432 }
433 }
434 if (my $exchanges = $h->{'exchanges'}) {
435 while (my ($symbol, $exchange) = each %$exchanges) {
436 if (defined $exchange) {
437 $data_changed{$symbol} |= set_exchange ($symbol, $exchange);
438 }
439 }
440 }
441 while (my ($symbol, $decimals) = each %decimals) {
442 if (defined $decimals) {
443 $data_changed{$symbol} |= set_decimals ($symbol, $decimals);
444 }
445 }
446  
447 my $symbol_list = [ keys %data_changed ];
448  
449 if (my $key = $h->{'url_tags_key'}) {
450 my $resp = $h->{'resp'};
451 foreach my $symbol (@$symbol_list) {
452 my $url = (defined $resp ? $resp->request->uri : undef);
453 my $etag = (defined $resp ? scalar $resp->header('ETag') : undef);
454 my $last_modified =(defined $resp ? $resp->last_modified : undef);
455  
456 App::Chart::Database->write_extra
457 ($symbol, "$key-URL", "$url"); # stringize URI object
458 App::Chart::Database->write_extra
459 ($symbol, "$key-ETag", $etag);
460 App::Chart::Database->write_extra
461 ($symbol, "$key-Last-Modified", $last_modified);
462 }
463 }
464  
465 if (my $key = $h->{'copyright_key'}) {
466 foreach my $symbol (@$symbol_list) {
467 App::Chart::Database->write_extra
468 ($symbol, $key, $h->{'copyright'});
469 }
470 }
471  
472 my $timestamp = timestamp_now();
473  
474 if (my $key = $h->{'recheck_key'}) {
475 my @recheck_list;
476 if (my $l = $h->{'recheck_list'}) {
477 @recheck_list = @$l;
478 }
479 if (my $pred = $h->{'recheck_pred'}) {
480 push @recheck_list,
481 grep { $pred->match($_) } keys %$database_symbols_hash;
482 }
483 if (DEBUG) { print "Recheck write ",join(' ',@recheck_list),"\n"; }
484 foreach my $symbol (@recheck_list) {
485 App::Chart::Database->write_extra ($symbol, $key, $timestamp);
486 }
487 }
488  
489 if ($h->{'last_download'}) {
490 foreach my $symbol (keys %data_changed) {
491 App::Chart::Database->write_extra ($symbol, 'last-download',
492 $timestamp);
493 }
494 consider_historical ($symbol_list);
495 }
496 consider_latest_from_daily ($h, $database_symbols_hash);
497 });
498  
499 ### data_changed: %data_changed
500 App::Chart::chart_dirbroadcast()->send ('data-changed', \%data_changed);
501 }
502  
503 sub consider_historical {
504 my ($symbol_list) = @_;
505  
506 my $all_list;
507 my $historical_list;
508  
509 foreach my $symbol (@$symbol_list) {
510 if (App::Chart::Database->symbol_is_historical ($symbol)) {
511 next; # already marked
512 }
513 my $reason = want_historical($symbol) // next;
514 download_message ($reason);
515  
516 my $dbh = App::Chart::DBI->instance;
517 $dbh->do ('UPDATE info SET historical=1 WHERE symbol=?',
518 {}, $symbol);
519  
520 require App::Chart::Gtk2::Symlist;
521 $all_list ||= App::Chart::Gtk2::Symlist::All->instance;
522 $historical_list ||= App::Chart::Gtk2::Symlist::Historical->instance;
523  
524 $all_list->delete_symbol ($symbol);
525 $historical_list->insert_symbol ($symbol);
526 }
527 }
528  
529 # return true if $symbol should be marked historical, meaning it has had no
530 # new daily data for a long time
531 #
532 sub want_historical {
533 my ($symbol) = @_;
534 my $last_download_timestamp
535 = App::Chart::Database->read_extra ($symbol, 'last-download')
536 // return undef; # no download attempted, not historical
537  
538 my $date = App::Chart::DBI->read_single
539 ('SELECT date FROM daily WHERE (symbol=?) AND (close NOTNULL)
540 ORDER BY date DESC LIMIT 1',
541 $symbol);
542 if (! defined $date) {
543 return __x('{symbol} no data at all, marked historical',
544 symbol => $symbol);
545 }
546 my $days = iso_timestamp_days_ago ($date, $last_download_timestamp);
547 if ($days > 21) {
548 return __x('{symbol} no data for {days} days, marked historical',
549 days => $days,
550 symbol => $symbol);
551 }
552 return undef;
553 }
554  
555 sub iso_timestamp_days_ago {
556 my ($iso, $prev_timestamp) = @_;
557 my ($prev_year,$prev_month,$prev_day) = timestamp_to_ymdhms($prev_timestamp);
558 return Date::Calc::Delta_Days (App::Chart::iso_to_ymd($iso),
559 $prev_year, $prev_month, $prev_day);
560 }
561  
562 sub consider_latest_from_daily {
563 my ($h) = @_;
564 my $dbh = App::Chart::DBI->instance;
565 my %latest_changed;
566 my $timestamp;
567  
568 my $database_symbols_hash = App::Chart::Database::database_symbols_hash();
569  
570 # find the newest and second newest data record of each symbol
571 my %data_newest;
572 my %data_second;
573 foreach my $data (@{$h->{'data'}}) {
574 my $symbol = $data->{'symbol'};
575 if ($data->{'date'} ge ($data_newest{$symbol}->{'date'} // '')) {
576 $data_second{$symbol} = $data_newest{$symbol};
577 $data_newest{$symbol} = $data;
578 } elsif ($data->{'date'} ge ($data_second{$symbol}->{'date'} // '')) {
579 $data_second{$symbol} = $data;
580 }
581 }
582  
583 foreach my $symbol (keys %data_newest) {
584 my $newest = $data_newest{$symbol};
585 my $date = $newest->{'date'};
586  
587 # For symbols in the database, if newest daily is >= latest quote then
588 # delete that quote in order to prefer the daily data in the database.
589 if (exists $database_symbols_hash->{$symbol}) {
590 my $latest_delete_sth = $dbh->prepare_cached
591 ('DELETE FROM latest WHERE symbol=? AND quote_date < ?');
592 if ($latest_delete_sth->execute ($symbol, $date)) {
593 $latest_changed{$symbol} = 1;
594 }
595 next;
596 }
597  
598 # For symbols not in the database, if the newest daily is >= latest quote
599 # then replace that quote with the daily.
600 #
601 # Times in the latest record are not considered, so it's possible a
602 # quote taken after close of trading will be deleted or overwritten.
603 # Would want something in the latest to say it's after the close ...
604  
605 my $latest_get_sth = $dbh->prepare_cached
606 ('SELECT last_date, name FROM latest WHERE symbol=?');
607 my ($last_date, $name, $dividend)
608 = $dbh->selectrow_array ($latest_get_sth, undef, $symbol);
609 if (defined $last_date && $last_date gt $date) { next; }
610  
611 # "name" from the daily, or retain name from existing latest record.
612 $name = $h->{'names'}->{$symbol} // $name;
613  
614 # "dividend" from existing latest record retained, but only if same date.
615 unless (defined $last_date && $last_date eq $date) {
616 undef $dividend;
617 }
618  
619 # change by difference from second newest daily, if have one
620 my $change = undef;
621 if (defined(my $second_close = $data_second{$symbol}->{'close'})) {
622 $change = App::Chart::decimal_sub ($newest->{'close'}, $second_close);
623 }
624  
625 $timestamp ||= timestamp_now();
626  
627 my $latest_set_sth = $dbh->prepare_cached
628 ('INSERT OR REPLACE INTO latest
629 (symbol, name, currency, exchange, dividend,
630 last_date, open, high, low, last, change, volume,
631 source, fetch_timestamp)
632 VALUES (?,?,?,?,?, ?,?,?,?,?,?,?, ?,?)');
633 $latest_set_sth->execute
634 ($symbol,
635 $name,
636 $h->{'currencies'}->{$symbol},
637 $h->{'exchanges'}->{$symbol},
638 $dividend,
639 #
640 $newest->{'date'},
641 $newest->{'open'},
642 $newest->{'high'},
643 $newest->{'low'},
644 $newest->{'close'},
645 $change,
646 $newest->{'volume'},
647 #
648 $h->{'source'},
649 $timestamp);
650 $latest_changed{$symbol} = 1;
651 }
652  
653 foreach my $dividend (@{$h->{'dividends'}}) {
654 my $latest_dividend_sth = $dbh->prepare_cached
655 ('UPDATE latest SET dividend=? WHERE symbol=? AND last_date=?');
656 my $symbol = $dividend->{'symbol'};
657 if ($latest_dividend_sth->execute ($dividend->{'amount'},
658 $symbol,
659 $dividend->{'ex_date'})) {
660 $latest_changed{$symbol} = 1;
661 }
662 }
663  
664 App::Chart::chart_dirbroadcast()->send ('latest-changed', \%latest_changed);
665  
666 require App::Chart::Annotation;
667 foreach my $symbol (keys %latest_changed) {
668 App::Chart::Annotation::Alert::update_alert ($symbol);
669 }
670 }
671  
672  
673 #------------------------------------------------------------------------------
674  
675 sub write_latest_group {
676 my ($h) = @_;
677 ### write_latest_group(): $h
678  
679 crunch_h ($h);
680 ### crunched: $h
681  
682 my $fetch_timestamp = timestamp_now();
683 my $prefer_decimals = $h->{'prefer_decimals'};
684 my $source = $h->{'source'}
685 or croak 'missing "source" for latest records';
686 my %latest;
687  
688 my $dbh = App::Chart::DBI->instance;
689 App::Chart::Database::call_with_transaction
690 ($dbh, sub {
691  
692 my $sth = $dbh->prepare_cached
693 ('INSERT OR REPLACE INTO latest
694 (symbol, name, month, exchange, currency,
695 quote_date, quote_time, bid, offer,
696 last_date, last_time, open, high, low, last, change, volume,
697 note, error, dividend, copyright, source,
698 fetch_timestamp, url, etag, last_modified)
699 VALUES (?,?,?,?,?, ?,?,?,?, ?,?,?,?,?,?,?,?, ?,?,?,?,?, ?,?,?,?)');
700  
701 my $resp = $h->{'resp'};
702 my $etag = (defined $resp ? scalar $resp->header('ETag') : undef);
703 my $last_modified = (defined $resp ? $resp->last_modified : undef);
704  
705 foreach my $data (@{$h->{'data'}}) {
706 my $symbol = $data->{'symbol'};
707 my $this_date = $data->{'date'};
708 if ($latest{$symbol}) {
709 my $got_date = $latest{$symbol}->{'date'};
710 if (! defined $got_date || ! defined $this_date) {
711 carp "write_latest_group: $source: two records for '$symbol', but no 'date' field";
712 if (DEBUG || 1) {
713 require Data::Dumper;
714 print Data::Dumper->Dump([$data,$latest{$symbol}],
715 ['data','latest-so-far']);
716 }
717 next;
718 }
719 if ($got_date ge $this_date) { next; }
720 }
721 $latest{$symbol} = $data;
722 }
723  
724 my $error = $h->{'error'};
725 if (! defined $error && defined $resp && ! $resp->is_success) {
726 $error = $resp->status_line;
727 }
728  
729 foreach my $data (values %latest) {
730 my $symbol = $data->{'symbol'};
731  
732 my $bid = $data->{'bid'};
733 my $offer = $data->{'offer'};
734  
735 # disallow 0 for prices
736 if ($bid && $bid == 0) { $bid = undef; }
737 if ($offer && $offer == 0) { $offer = undef; }
738  
739 my $quote_date = crunch_date ($data->{'quote_date'});
740 my $quote_time = crunch_time ($data->{'quote_time'});
741 if ($quote_time && ! $quote_date) {
742 croak "quote_time without quote_date for $symbol";
743 }
744 # default quote date/time to now
745 if (($bid || $offer) && ! $quote_date) {
746 my $symbol_timezone = App::Chart::TZ->for_symbol ($symbol);
747 ($quote_date, $quote_time)
748 = $symbol_timezone->iso_date_time
749 (time() - 60 * ($data->{'quote_delay_minutes'} || 0));
750 }
751  
752 my $last_date = crunch_date ($data->{'last_date'} || $data->{'date'});
753 my $last_time = crunch_time ($data->{'last_time'});
754  
755 my $open = $data->{'open'};
756 my $high = $data->{'high'};
757 my $low = $data->{'low'};
758 my $last = $data->{'last'} || $data->{'close'};
759 my $change = $data->{'change'};
760 my $prev = crunch_price ($data->{'prev'}, $prefer_decimals);
761 my $volume = $data->{'volume'};
762  
763 if (! defined $last) {
764 # if there's no last price then try to use the prev
765 $open = $high = $low = undef;
766 $last = $prev;
767 $prev = undef;
768 $change = undef;
769 $last_date = undef;
770 $last_time = undef;
771  
772 } elsif (! defined $change) {
773 # if no change given then try to calculate it from last and prev
774  
775 if (! defined $prev) {
776 # if no prev then look for one among other $data records, as for
777 # when the group is a few consecutive daily data
778 my $prev_date;
779 foreach my $data (@{$h->{'data'}}) {
780 if ($data->{'symbol'} eq $symbol
781 && exists $data->{'date'}
782 && $data->{'date'} lt $last_date
783 && (! $prev_date
784 || $data->{'date'} gt $prev_date)) {
785 $prev_date = $data->{'date'};
786 $prev = $data->{'close'};
787 }
788 }
789 }
790 if ($prev) {
791 $change = App::Chart::decimal_sub ($last, $prev);
792 }
793 }
794  
795 $sth->execute ($symbol,
796 $h->{'names'}->{$symbol},
797 $data->{'month'},
798 $h->{'exchanges'}->{$symbol},
799 $h->{'currencies'}->{$symbol},
800  
801 $quote_date, $quote_time,
802 $bid, $offer,
803  
804 $last_date, $last_time,
805 $open, $high, $low, $last, $change, $volume,
806  
807 $data->{'note'},
808 $data->{'error'} || $error,
809 $data->{'dividend'},
810 $h->{'copyright'},
811 $source,
812  
813 $fetch_timestamp,
814 $h->{'url'},
815 $etag,
816 $last_modified);
817 $sth->finish;
818 }
819 });
820  
821 App::Chart::chart_dirbroadcast()->send ('latest-changed', \%latest);
822  
823 require App::Chart::Annotation;
824 foreach my $symbol (keys %latest) {
825 App::Chart::Annotation::Alert::update_alert ($symbol);
826 }
827 }
828  
829 sub iso_to_MMM_YY {
830 my ($iso) = @_;
831 my ($year, $month, $day) = App::Chart::iso_to_ymd ($iso);
832 return sprintf ("%.3s %02d",
833 uc(Date::Calc::Month_to_Text ($month)),
834 $year % 100);
835 }
836  
837 #------------------------------------------------------------------------------
838  
839 my $iso_date_re = qr/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$/;
840  
841 my %date_format_to_func
842 = ('ymd' => \&App::Chart::Download::Decode_Date_YMD_to_iso,
843 'dmy' => \&App::Chart::Download::Decode_Date_EU_to_iso,
844 'mdy' => \&App::Chart::Download::Decode_Date_US_to_iso);
845 sub noop {
846 return $_[0];
847 }
848  
849 my %date_format_to_month_func
850 = ('ymd' => \&crunch_month_ymd);
851  
852 sub crunch_month_ymd {
853 my ($str) = @_;
854 my ($year, $month, $day) = Date::Calc::Decode_Date_EU ($str);
855 if (! defined $year) {
856 croak "unrecognised month string: $str";
857 }
858 if (defined $day) {
859 if ($day != 1) { croak "month with day!=1: '$str' got $day"; }
860 } else {
861 $day = 1;
862 }
863 return App::Chart::ymd_to_iso ($year, $month, $day);
864 }
865  
866 sub crunch_h {
867 my ($h) = @_;
868 my $database_symbols_hash = App::Chart::Database::database_symbols_hash();
869  
870 # ignore undef where expecting hashrefs in 'data' and 'dividends' arefs
871 foreach my $elem ('data',
872 'dividends') {
873 my $aref = $h->{$elem} // next;
874 @$aref = grep {
875 defined $_
876 # && App::Chart::Database->symbol_exists($_->{'symbol'})
877 } @$aref;
878 }
879  
880 my $suffix = $h->{'suffix'};
881 my $month_format = $h->{'month_format'};
882 my $prefer_decimals = $h->{'prefer_decimals'};
883  
884 my $date_format = delete $h->{'date_format'};
885 my $date_func = ($date_format ? $date_format_to_func{$date_format} : \&noop)
886 || croak "Unrecognised date_format '$date_format'";
887 # my $month_func = $date_format ? $date_format_to_month_func{$date_format} : \&noop;
888  
889 my %currencies; $h->{'currencies'} = \%currencies;
890 my %isins; $h->{'isins'} = \%isins;
891 my %names; $h->{'names'} = \%names;
892 my %exchanges; $h->{'exchanges'} = \%exchanges;
893  
894 foreach my $info (@{$h->{'info'}}) {
895 my $symbol = $info->{'symbol'}
896 or croak "write_daily_group: missing symbol in info record";
897 if (! exists $database_symbols_hash->{$symbol}) { next; }
898  
899 $names{$symbol} ||= delete $info->{'name'};
900 $currencies{$symbol} ||= delete $info->{'currency'};
901 $exchanges{$symbol} ||= delete $info->{'exchange'};
902 $isins{$symbol} ||= delete $info->{'isin'};
903 }
904  
905 foreach my $data (@{$h->{'data'}}) {
906 my $month = $data->{'month'};
907 if (defined $month) {
908 # $month = $data->{'month'} = $month_func->($month);
909 $month =~ $iso_date_re or croak "Bad month value '$month'";
910 }
911  
912 my $symbol = $data->{'symbol'};
913 if (! defined $symbol) {
914 # symbols built from commodity + month
915 my $commodity = $data->{'commodity'}
916 // croak "neither symbol nor commodity in 'data' element";
917 $month // croak "Group data: no 'month' to go with 'commodity' in data element";
918 $symbol = $data->{'symbol'}
919 = $commodity . ' ' . iso_to_MMM_YY($month) . $suffix;
920 }
921 # if ($month_format eq 'MMM_YY') {
922 # $month = iso_to_MMM_YY ($month);
923 # } else {
924 # croak "unrecognised month format: $month_format";
925 # }
926 }
927  
928 if ($h->{'front_month'}) {
929 my %front;
930 foreach my $data (@{$h->{'data'}}) {
931 my $symbol = $data->{'symbol'};
932 my $front_symbol
933 = App::Chart::symbol_commodity($symbol)
934 . App::Chart::symbol_suffix($symbol);
935 if (! $front{$front_symbol}
936 || $data->{'month'} gt $front{$front_symbol}->{'month'}) {
937 $front{$front_symbol} = $data;
938 }
939 }
940  
941 while (my ($symbol, $data) = each %front) {
942 $data = { %$data };
943 $data->{'symbol'} = $symbol;
944 push @{$h->{'data'}}, $data;
945 }
946 }
947  
948 foreach my $data (@{$h->{'data'}}) {
949  
950 foreach my $field ('date', 'quote_date', 'last_date') {
951 if (defined $data->{$field}) {
952 $data->{$field} = crunch_date ($data->{$field}, $date_format);
953 }
954 }
955  
956 # empty volume or openint taken to be no data (as opposed to '0' for
957 # zero volume or int)
958 foreach my $field ('volume', 'openint') {
959 if (defined $data->{$field} && $data->{$field} eq '') {
960 $data->{$field} = undef;
961 }
962 }
963  
964 if (my $sessions = delete $data->{'sessions'}) {
965 my @sessions = grep {defined} map {crunch_price($_)} @$sessions;
966 $data->{'open'} = $sessions[0];
967 ($data->{'low'}, $data->{'high'}) = List::MoreUtils::minmax (@sessions);
968 $data->{'close'} = $sessions[-1];
969 }
970  
971 if (exists $data->{'change'}) {
972 $data->{'change'} = crunch_change ($data->{'change'}, $prefer_decimals);
973 }
974 foreach my $field (qw(bid offer open high low close last)) {
975 if (exists $data->{$field}) {
976 $data->{$field} = crunch_price ($data->{$field}, $prefer_decimals);
977 }
978 }
979 foreach my $field (qw(volume openint)) {
980 if (exists $data->{$field}) {
981 $data->{$field} = crunch_number ($data->{$field});
982 }
983 }
984  
985 my $symbol = $data->{'symbol'};
986 $currencies{$symbol} ||= delete $data->{'currency'} || $h->{'currency'};
987 $names{$symbol} ||= delete $data->{'name'} || $h->{'name'};
988 $exchanges{$symbol} ||= delete $data->{'exchange'};
989 $isins{$symbol} ||= delete $data->{'isin'};
990 }
991  
992 foreach my $dividend (@{$h->{'dividends'}}) {
993 foreach my $field ('ex_date', 'record_date', 'pay_date') {
994 if (defined $dividend->{$field}) {
995 $dividend->{$field} = crunch_date ($dividend->{$field}, $date_format);
996 }
997 }
998 $dividend->{'ex_date'}
999 or croak 'Group data: missing ex_date in dividend record';
1000  
1001 foreach my $field (qw(amount imputation)) {
1002 if (exists $dividend->{$field}) {
1003 $dividend->{$field} = crunch_price ($dividend->{$field}, $prefer_decimals);
1004 }
1005 }
1006 }
1007  
1008 foreach my $split (@{$h->{'splits'}}) {
1009 if (defined $split->{'date'}) {
1010 $split->{'date'} = crunch_date ($split->{'date'}, $date_format);
1011 }
1012 $split->{'date'}
1013 or croak "Group data: missing 'date' in split record";
1014 }
1015  
1016 # whitespace in names, and possible leading/trailing in isins
1017 foreach my $href (\%names, \%currencies, \%exchanges, \%isins) {
1018 hash_delete_undefs ($href);
1019 }
1020 foreach (values %names, values %isins) {
1021 $_ = App::Chart::collapse_whitespace ($_);
1022 }
1023  
1024 if (eval { require Business::ISIN; 1 }) {
1025 my $bi = Business::ISIN->new;
1026 while (my ($symbol, $isin) = each %isins) {
1027 $bi->set ($isin);
1028 if ($bi->is_valid) { next; }
1029 warn "$symbol ISIN '$isin' is invalid, ignoring: ", $bi->error;
1030 delete $isins{$symbol};
1031 }
1032 }
1033 }
1034  
1035 sub hash_delete_undefs {
1036 my ($href) = @_;
1037 while (my ($key, $value) = each %$href) {
1038 if (! defined $value) {
1039 delete $href->{$key};
1040 }
1041 }
1042 }
1043  
1044 sub crunch_date {
1045 my ($str, $format) = @_;
1046 $str = crunch_empty_undef ($str);
1047 if (! defined $str) { return $str; }
1048  
1049 if (defined $format) {
1050 my $func = $date_format_to_func{$format};
1051 defined $func or croak "Unrecognised date_format spec: $format";
1052 $str = &$func ($str);
1053 }
1054 $str =~ $iso_date_re or croak "Bad date '$str'";
1055 return $str;
1056 }
1057  
1058 sub crunch_price {
1059 my ($str, $prefer_decimals) = @_;
1060 $str = crunch_change ($str, $prefer_decimals) // return undef;
1061  
1062 if (str_is_zero ($str)) { return undef; }
1063 return $str;
1064 }
1065 sub crunch_change {
1066 my ($str, $prefer_decimals) = @_;
1067 $str = crunch_number ($str) // return undef;
1068  
1069 if ($str eq '') { return undef; } # empty
1070 if (uc($str) eq 'CLOSED') { return undef; } # RBA 2003-2006.xls
1071 if ($str eq 'unch') { return '0'; } # unchanged
1072 if (defined $prefer_decimals) {
1073 return App::Chart::Download::trim_decimals ($str, $prefer_decimals);
1074 } else {
1075 return $str;
1076 }
1077 }
1078  
1079 sub crunch_number {
1080 my ($str) = @_;
1081 if (! defined $str) { return undef; }
1082  
1083 $str =~ s/$RE{ws}{crop}//go; # leading and trailing whitespace
1084 $str =~ s/^\+//; # leading + sign
1085 $str =~ s/^0+([1-9]|0\.|0$)/$1/; # leading extra zeros
1086  
1087 if ($str eq ''
1088 || $str eq '-'
1089 || $str eq 'N/A'
1090 || $str eq 'n/a') {
1091 return undef;
1092 }
1093 $str =~ s/,//g; # commas for thousands
1094 return $str;
1095 }
1096  
1097 sub crunch_time {
1098 my ($str) = @_;
1099 $str = crunch_empty_undef ($str);
1100 if (! defined $str) { return undef; }
1101  
1102 $str =~ /^([0-9]?[0-9])(:[0-9][0-9])(:[0-9][0-9])?([ap]m)?$/i
1103 or croak "bad time '$str'";
1104 my $hour = $1;
1105 my $minute = $2;
1106 my $second = $3;
1107 my $am_pm = $4;
1108 $second //= ':00';
1109 if (defined $am_pm && lc $am_pm eq 'pm') { $hour += 12; }
1110 $hour = sprintf '%02d', $hour;
1111 return "$hour$minute$second";
1112 }
1113  
1114 sub crunch_empty_undef {
1115 my ($str) = @_;
1116 if (! defined $str) { return $str; }
1117 $str =~ s/$RE{ws}{crop}//go; # leading and trailing whitespace
1118  
1119 # eg. string "N/A" in dates and times from Yahoo
1120 if ($str eq '' || $str eq 'N/A') { return undef; }
1121 return $str;
1122 }
1123  
1124  
1125 #------------------------------------------------------------------------------
1126  
1127 sub set_symbol_name {
1128 my ($symbol, $name) = @_;
1129 my $dbh = App::Chart::DBI->instance;
1130 my $sth = $dbh->prepare_cached('UPDATE info SET name=? WHERE symbol=?');
1131 my $changed = $sth->execute($name, $symbol);
1132 $sth->finish();
1133 return $changed;
1134 }
1135 sub set_currency {
1136 my ($symbol, $currency) = @_;
1137 my $dbh = App::Chart::DBI->instance;
1138 my $sth = $dbh->prepare_cached('UPDATE info SET currency=? WHERE symbol=?');
1139 my $changed = $sth->execute($currency, $symbol);
1140 $sth->finish();
1141 return $changed;
1142 }
1143 sub set_exchange {
1144 my ($symbol, $exchange) = @_;
1145 my $dbh = App::Chart::DBI->instance;
1146 my $sth = $dbh->prepare_cached('UPDATE info SET exchange=? WHERE symbol=?');
1147 my $changed = $sth->execute($exchange, $symbol);
1148 $sth->finish();
1149 return $changed;
1150 }
1151 sub set_decimals {
1152 my ($symbol, $decimals) = @_;
1153 my $dbh = App::Chart::DBI->instance;
1154 my $sth = $dbh->prepare_cached('UPDATE info SET decimals=? WHERE symbol=?');
1155 my $changed = $sth->execute($decimals, $symbol);
1156 $sth->finish();
1157 return $changed;
1158 }
1159 sub set_isin {
1160 my ($symbol, $isin) = @_;
1161 my $dbh = App::Chart::DBI->instance;
1162 my $sth = $dbh->prepare_cached('UPDATE info SET isin=? WHERE symbol=?');
1163 my $changed = $sth->execute($isin, $symbol);
1164 $sth->finish();
1165 return $changed;
1166 }
1167  
1168  
1169 #------------------------------------------------------------------------------
1170  
1171 # return true if $timestamp string is within the past $seconds from now
1172 # also return true if $timestamp is some strange future value
1173 sub timestamp_within {
1174 my ($timestamp, $seconds) = @_;
1175 if (! defined $timestamp) { return 0; } # undef stamp always out of range
1176 my ($lo, $hi) = timestamp_range ($seconds);
1177 return (($timestamp ge $lo) && ($timestamp le $hi));
1178 }
1179 sub timestamp_range {
1180 my ($seconds) = @_;
1181 my $t = time();
1182 my $lo = $t - $seconds;
1183 my $hi = $t + 6*3600; # 2 hours future
1184 return (timet_to_timestamp($lo),
1185 timet_to_timestamp($hi));
1186 }
1187 sub timestamp_now {
1188 return timet_to_timestamp(time());
1189 }
1190 sub timet_to_timestamp {
1191 my ($t) = @_;
1192 return POSIX::strftime ('%Y-%m-%d %H:%M:%S+00:00', gmtime($t));
1193 }
1194 sub timestamp_to_ymdhms {
1195 my ($timestamp) = @_;
1196 return split /[- :+]/, $timestamp;
1197 }
1198 sub timestamp_to_timet {
1199 my ($timestamp) = @_;
1200 my ($year, $month, $day, $hour, $minute, $second)
1201 = timestamp_to_ymdhms($timestamp);
1202 require Time::Local;
1203 return Time::Local::timegm_modern
1204 ($second, $minute, $hour, $day, $month-1, $year);
1205 }
1206  
1207  
1208 #------------------------------------------------------------------------------
1209  
1210 sub tdate_strftime {
1211 my ($format, $tdate) = @_;
1212 my ($year, $month, $day) = App::Chart::tdate_to_ymd ($tdate);
1213 require App::Chart::Timebase;
1214 return App::Chart::Timebase::strftime_ymd ($format, $year, $month, $day);
1215 }
1216  
1217 sub tdate_range_string {
1218 my ($lo, $hi) = @_;
1219 if (@_ < 2) { $hi = $lo; }
1220 my $d_fmt = $App::Chart::option{'d_fmt'};
1221 if ($lo == $hi) {
1222 return tdate_strftime ($d_fmt, $lo);
1223 } else {
1224 return __x('{lodate} to {hidate}',
1225 lodate => tdate_strftime ($d_fmt, $lo),
1226 hidate => tdate_strftime ($d_fmt, $hi));
1227 }
1228 }
1229  
1230 sub symbol_range_string {
1231 my ($symbol_list) = @_;
1232 if (@$symbol_list == 0) {
1233 return '';
1234 } elsif (@$symbol_list == 1) {
1235 return $symbol_list->[0];
1236 } else {
1237 return __x('{start_symbol} to {end_symbol}',
1238 start_symbol => $symbol_list->[0],
1239 end_symbol => $symbol_list->[-1]);
1240 }
1241 }
1242  
1243 #------------------------------------------------------------------------------
1244  
1245 sub weekday_date_after_time {
1246 return App::Chart::tdate_to_iso (weekday_tdate_after_time (@_));
1247 }
1248 sub weekday_tdate_after_time {
1249 my ($after_hour,$after_min, $timezone, $offset) = @_;
1250  
1251 local $Tie::TZ::TZ = $timezone->tz;
1252 my ($year,$month,$day, $hour,$min,$sec, $doy,$dow,$dst)
1253 = Date::Calc::Localtime();
1254  
1255 my $tdate = App::Chart::ymd_to_tdate_floor ($year,$month,$day)
1256 + ($offset // 0);
1257  
1258 if ($dow >= 6 # Saturday or Sunday
1259 || ($hour*60+$min < $after_hour*60+$after_min)) {
1260 $tdate--;
1261 }
1262 return $tdate;
1263 }
1264  
1265 #------------------------------------------------------------------------------
1266  
1267 sub download {
1268 my (%options) = @_;
1269  
1270 my @symbol_list = ();
1271 {
1272 my $symbol_list = $options{'symbol_list'}
1273 || croak "download() missing symbol_list\n";
1274 @symbol_list = @$symbol_list;
1275 }
1276  
1277 @symbol_list = List::MoreUtils::uniq (@symbol_list);
1278 verbose_message (__('Download:'), @symbol_list);
1279  
1280 foreach my $symbol (@symbol_list) {
1281 App::Chart::symbol_setups ($symbol);
1282 }
1283 App::Chart::Database->add_symbol (@symbol_list);
1284  
1285 require App::Chart::DownloadHandler;
1286 my $all_ok = 1;
1287 foreach my $handler (@App::Chart::DownloadHandler::handler_list) {
1288 my @this_list = grep {$handler->match($_)} @symbol_list;
1289 my $ok = $handler->download (\@this_list);
1290 if (! $ok) { $all_ok = 0; }
1291 }
1292  
1293 # my %handler_result = ();
1294 # foreach my $symbol (@symbol_list) {
1295 #
1296 # my @handlers = App::Chart::DownloadHandler->handlers_for_symbol ($symbol);
1297 # foreach my $handler (@handlers) {
1298 # if (exists $handler_result{$handler}) {
1299 # if (! $handler_result{$handler}) { $all_ok = 0; }
1300 # next;
1301 # }
1302 #
1303 # my @this_list = grep { my $symbol = $_;
1304 # List::MoreUtils::all
1305 # {$_->match($symbol)} @handlers
1306 # } @symbol_list;
1307 # my $ok = $handler->download (\@this_list);
1308 # $handler_result{$handler} = $ok;
1309 # }
1310 #
1311 # }
1312 status (__('Checking historical'));
1313 if ($all_ok) {
1314 consider_historical (\@symbol_list);
1315 }
1316 }
1317  
1318 # return a list of symbols, either just ($symbol), or if $symbol has
1319 # wildcards then the result of matching that in the "all" list
1320 sub symbol_glob {
1321 my ($symbol) = @_;
1322  
1323 if ($symbol =~ /[*?]/) {
1324 require Text::Glob;
1325 require App::Chart::Gtk2::Symlist::All;
1326 my $symlist = App::Chart::Gtk2::Symlist::All->instance;
1327 my $regexp = Text::Glob::glob_to_regex ($symbol);
1328 my @list = grep {$_ =~ $regexp} $symlist->symbols;
1329 if (! @list) {
1330 print __x("Warning, pattern \"{pattern}\" doesn't match anything in the database, ignoring\n",
1331 pattern => $symbol);
1332 }
1333 return @list;
1334 } else {
1335 return ($symbol);
1336 }
1337 }
1338  
1339 sub command_line_download {
1340 my ($class, $output, $args) = @_;
1341 my $hash;
1342  
1343 if ($output eq 'tty') {
1344 if (-t STDOUT) {
1345 binmode (STDOUT, ':via(EscStatus)')
1346 or die 'Cannot push EscStatus';
1347 } else {
1348 require PerlIO::via::EscStatus::ShowNone;
1349 binmode (STDOUT, ':via(EscStatus::ShowNone)')
1350 or die 'Cannot push EscStatus::ShowNone';
1351 }
1352 } elsif ($output eq 'all-status') {
1353 require PerlIO::via::EscStatus::ShowAll;
1354 binmode (STDOUT, ':via(EscStatus::ShowAll)')
1355 or die 'Cannot push EscStatus::ShowAll';
1356 }
1357  
1358 if (! @$args) {
1359 print __"No symbols specified to download\n";
1360 return;
1361 }
1362  
1363 my @symbol_list = ();
1364 foreach my $arg (@$args) {
1365 if (ref $arg) {
1366 # only what's already in the database
1367 $hash ||= App::Chart::Database::database_symbols_hash();
1368 my @list = grep {exists $hash->{$_}} $arg->symbols;
1369 push @symbol_list, @list;
1370 if (! @list) {
1371 print __x("Warning, no symbols in \"{symlist}\" are currently in the database\n(only symbols already in the database are downloaded from lists)\n",
1372 symlist => $arg->name);
1373 }
1374 } else {
1375 push @symbol_list, symbol_glob ($arg);
1376 }
1377 }
1378  
1379 App::Chart::Download::download (symbol_list => \@symbol_list);
1380  
1381 require App::Chart::LatestHandler;
1382 App::Chart::LatestHandler->download (\@symbol_list);
1383  
1384 status ('');
1385 }
1386  
1387 #------------------------------------------------------------------------------
1388  
1389 sub iso_to_tdate_floor {
1390 my ($str) = @_;
1391 my ($year, $month, $day) = App::Chart::iso_to_ymd ($str);
1392 return App::Chart::ymd_to_tdate_floor ($year, $month, $day);
1393 }
1394  
1395 sub iso_to_tdate_ceil {
1396 my ($str) = @_;
1397 my ($year, $month, $day) = App::Chart::iso_to_ymd ($str);
1398 return App::Chart::ymd_to_tdate_ceil ($year, $month, $day);
1399 }
1400  
1401 sub tdate_today {
1402 my ($timezone) = @_;
1403 $timezone //= App::Chart::TZ->loco;
1404 my ($year, $month, $day) = $timezone->ymd;
1405 return App::Chart::ymd_to_tdate_floor ($year, $month, $day);
1406 }
1407  
1408 my $default_download_tdates = 5 * 265; # 5 years
1409  
1410 sub start_tdate_for_update {
1411 my (@symbol_list) = @_;
1412 if (! @symbol_list) { croak "start_tdate_for_update(): no symbols"; }
1413 my $ret;
1414 foreach my $symbol (@symbol_list) {
1415 my $iso = App::Chart::DBI->read_single
1416 ('SELECT date FROM daily WHERE symbol=? ORDER BY date DESC LIMIT 1',
1417 $symbol);
1418 if (! defined $iso) {
1419 return (tdate_today() - $default_download_tdates);
1420 }
1421 my $tdate = iso_to_tdate_floor ($iso) + 1;
1422 $ret = App::Chart::min_maybe ($ret, $tdate);
1423 }
1424 return $ret;
1425 }
1426  
1427 sub tdate_today_after {
1428 my ($after_hour, $after_minute, $timezone) = @_;
1429  
1430 { local $Tie::TZ::TZ = $timezone->tz;
1431 my ($year,$month,$day, $hour,$min,$sec, $doy,$dow,$dst) =
1432 Date::Calc::System_Clock();
1433  
1434 my $tdate = App::Chart::ymd_to_tdate_floor ($year, $month, $day);
1435 if ($dow <= 5 # is a weekday
1436 && (App::Chart::hms_to_seconds ($hour, $min, 0)
1437 < App::Chart::hms_to_seconds ($after_hour, $after_minute, 0))) {
1438 $tdate--;
1439 }
1440 return $tdate;
1441 }
1442 }
1443  
1444  
1445 #-----------------------------------------------------------------------------
1446 # selecting among possibly overlapping files
1447  
1448 # $files is an arrayref containing hash records with keys
1449 #
1450 # lo_tdate,hi_tdate inclusive coverage of the record
1451 # lo_year,hi_year alterative form for date range
1452 # cost size of the file in bytes
1453 #
1454 sub choose_files {
1455 my ($files, $lo_tdate, $hi_tdate) = @_;
1456 if ($lo_tdate > $hi_tdate) { return []; }
1457  
1458 if (DEBUG) { print "choose_files $lo_tdate to $hi_tdate\n"; }
1459  
1460 foreach my $f (@$files) {
1461 if (! defined $f->{'lo_tdate'}) {
1462 if (my $m = $f->{'month_iso'}) {
1463 $f->{'lo_tdate'} = App::Chart::Download::iso_to_tdate_ceil ($m);
1464 } elsif ($f->{'lo_year'}) {
1465 $f->{'lo_tdate'}
1466 = App::Chart::ymd_to_tdate_ceil ($f->{'lo_year'}, 1, 1);
1467 } else {
1468 croak 'choose_files: missing lo date';
1469 }
1470 }
1471  
1472 if (! defined $f->{'hi_tdate'}) {
1473 if (my $m = $f->{'month_iso'}) {
1474 $f->{'hi_tdate'}
1475 = tdate_end_of_month (App::Chart::Download::iso_to_tdate_ceil ($m));
1476 } elsif ($f->{'hi_year'}) {
1477 $f->{'hi_tdate'}
1478 = App::Chart::ymd_to_tdate_floor($f->{'hi_year'}, 12, 31);
1479 } else {
1480 croak 'choose_files: missing hi date';
1481 }
1482 }
1483 }
1484 if (DEBUG >= 2) { require Data::Dumper;
1485 print Data::Dumper::Dumper($files); }
1486  
1487 # restrict wanted range to what's available
1488 my $lo_available = min (map {$_->{'lo_tdate'}} @$files);
1489 my $hi_available = max (map {$_->{'hi_tdate'}} @$files);
1490 $lo_tdate = max ($lo_tdate, $lo_available);
1491 $hi_tdate = min ($hi_tdate, $hi_available);
1492 if (DEBUG) { print " available $lo_available to $hi_available\n";
1493 print " restricted range $lo_tdate to $hi_tdate\n"; }
1494 if ($lo_tdate > $hi_tdate) { return []; }
1495  
1496 # ignore file elements not covering any of the desired range
1497 $files = [ grep {App::Chart::overlap_inclusive_p ($lo_tdate, $hi_tdate,
1498 $_->{'lo_tdate'},
1499 $_->{'hi_tdate'})}
1500 @$files ];
1501  
1502 # Algorithm::ChooseSubsets would be another way to iterate, or
1503 # Math::Subset::List to get all combinations
1504 my $best_cost;
1505 my $best_files;
1506 foreach my $this_files (all_combinations ($files)) {
1507 if (! cover_p ($this_files, $lo_tdate, $hi_tdate)) { next; }
1508 my $cost = List::Util::sum (map {$_->{'cost'}||0} @$this_files);
1509 $cost += $App::Chart::option{'http_get_cost'} * scalar(@$this_files);
1510 if (! defined $best_cost || $cost < $best_cost) {
1511 $best_cost = $cost;
1512 $best_files = $this_files;
1513 }
1514 }
1515 return $best_files;
1516 }
1517  
1518 # return true if the set of file records in arrayref $files covers all of
1519 # $lo_tdate through $hi_tdate inclusive
1520 #
1521 sub cover_p {
1522 my ($files, $lo_tdate, $hi_tdate) = @_;
1523 require Set::IntSpan::Fast;
1524 my $set = Set::IntSpan::Fast->new;
1525 foreach my $f (@$files) {
1526 $set->add_range ($f->{'lo_tdate'}, $f->{'hi_tdate'});
1527 }
1528 $set->contains_all_range ($lo_tdate, $hi_tdate);
1529 }
1530  
1531 # return a list which is all the combinations of elements of @$aref
1532 # for example $aref == [ 10, 20 ] would return ([], [10], [20], [10,20])
1533 # there's 2**N combinations for aref length N
1534 #
1535 sub all_combinations {
1536 my ($aref) = @_;
1537 my @ret = ([]);
1538 foreach my $i (0 .. $#$aref) {
1539 push @ret, map {[ @$_, $aref->[$i] ]} @ret;
1540 }
1541 return @ret;
1542 }
1543  
1544 # return the last tdate in the month containing the given $tdate
1545 sub tdate_end_of_month {
1546 my ($tdate) = @_;
1547 my ($year, $month, $day) = App::Chart::tdate_to_ymd ($tdate);
1548 ($year, $month, $day) = Date::Calc::Add_Delta_YM ($year, $month, $day, 0,1);
1549 $day = 1;
1550 ($year, $month, $day) = Date::Calc::Add_Delta_Days ($year, $month, $day, -1);
1551 return App::Chart::ymd_to_tdate_floor ($year, $month, $day);
1552 }
1553  
1554 1;
1555 __END__
1556  
1557 =for stopwords url TTY LF whitespace undef YYYY-MM-DD GBP ISIN tdate
1558  
1559 =head1 NAME
1560  
1561 App::Chart::Download -- download functions
1562  
1563 =cut
1564  
1565 # =head1 HTTP FUNCTIONS
1566 #
1567 # =over 4
1568 #
1569 # =item C<< $resp = App::Chart::Download->get ($url, key=>value,...) >>
1570 #
1571 # Download the given C<$url> and return a C<HTTP::Response> object. The
1572 # following key/value options are accepted.
1573 #
1574 # method default 'GET'
1575 # data body data for the request
1576 # etag from previous get of this url
1577 # last_modified from previous get of this url
1578 #
1579 # A C<"POST"> can be done by setting C<method> accordingly and passing
1580 # C<data>. C<etag> and/or C<last_modified> can be given to avoid a
1581 # re-download of url if unchanged (response status 304).
1582 #
1583 # =item C<< App::Chart::Download::status ($str, $str, ...) >>
1584 #
1585 # Join the argument strings together, with spaces between, and print them as
1586 # the current download status. Subsequent HTTP downloads through
1587 # C<App::Chart::UserAgent> will append their progress to this status too.
1588 #
1589 # =item C<< App::Chart::Download::download_message ($str, $str, ...) >>
1590 #
1591 # Join the argument strings together, with spaces between, and print them and
1592 # a newline as a download message. This differs from an ordinary C<print> in
1593 # that on a TTY it first erases anything from C<status> above (or checks the
1594 # message itself is long enough to overwrite).
1595 #
1596 # =back
1597 #
1598 # =head1 PARSING FUNCTIONS
1599 #
1600 # =over 4
1601 #
1602 # =item App::Chart::Download::split_lines ($str)
1603 #
1604 # Return a list of the lines in C<$str> separated by CR or LF, with trailing
1605 # whitespace stripped, and blank lines (entirely whitespace) removed.
1606 #
1607 # =item App::Chart::Download::trim_decimals ($str, $want_decimals)
1608 #
1609 # Return C<$str> with trailing zero decimal places trimmed off to leave
1610 # C<$want_decimals>. If C<$str> doesn't look like a number, or is undef, then
1611 # it's returned unchanged.
1612 #
1613 # =item App::Chart::Download::str_is_zero ($str)
1614 #
1615 # Return true if C<$str> is a zero number, like "0", "00", "0.00", ".000".
1616 #
1617 # =item C<< App::Chart::Download::cents_to_dollars ($str) >>
1618 #
1619 # C<$str> is a number like "12.5" in cents. Return it with the decimal point
1620 # shifted to be expressed in dollars like "0.125".
1621 #
1622 # =back
1623 #
1624 # =head1 DATE/TIME FUNCTIONS
1625 #
1626 # =over 4
1627 #
1628 # =item App::Chart::Download::month_to_nearest_year ($month)
1629 #
1630 # C<$month> is in the range 1 to 12. Return a year, as a number like 2007, to
1631 # go with that month, so that the combination is within +/- 6 months of today.
1632 #
1633 # =item C<< App::Chart::Download::Decode_Date_EU_to_iso ($str) >>
1634 #
1635 # Decode a date in the form day/month/year using
1636 # C<Date::Calc::Decode_Date_EU>, and return an ISO format date string like
1637 # "2007-10-26".
1638 #
1639 # =item App::Chart::Download::Decode_Date_YMD ($str)
1640 #
1641 # Decode a date in the form year/month/day and return C<($year, $month,
1642 # $day)>, similar to what C<Date::Calc> does.
1643 #
1644 # The month given can be a number or a name in English and is always returned
1645 # as a number. Any separator can be used between the components and leading
1646 # and trailing whitespace is ignored. If the string is unrecognised the
1647 # return is an empty list C<()>.
1648 #
1649 # =item App::Chart::Download::Decode_Date_YMD_to_iso ($str)
1650 #
1651 # Decode a date using C<App::Chart::Download::Decode_Date_YMD> above and return
1652 # an ISO format string "YYYY-MM-DD". An error is thrown if C<$str> is
1653 # invalid.
1654 #
1655 # =item App::Chart::Download::date_parse_to_iso ($str)
1656 #
1657 # unused?
1658 #
1659 # Apply Date::Parse::strptime() to C<$str> and return an ISO format date
1660 # string like "2007-10-26" for the result. An error is thrown if C<$str> is
1661 # unrecognisable.
1662 #
1663 # =back
1664 #
1665 # =item weekday_date_after_time ($hour,$min, $timezone, [$offset])
1666 #
1667 # Return an an ISO format date string like C<"2008-08-20"> which is a weekday,
1668 # giving today on a weekday after C<$hour>,C<$min>, or the previous weekday if
1669 # before that time or any time on a weekend.
1670 #
1671 # C<$offset> is a number of weekdays to step forward (or negative for back) on
1672 # the return value.
1673 #
1674 # For example if today's trading data is available after 5pm then a call like
1675 #
1676 # weekday_date_after_time (17,0, $my_zone)
1677 #
1678 # would give yesterday until 5pm, and today after that, and give Friday all
1679 # through the weekend. If trading data is not available until 9am the
1680 # following weekday then a call like
1681 #
1682 # weekday_date_after_time (9,0, $my_zone, -1)
1683 #
1684 # would return the day before yesterday until 9am, and yesterday after that,
1685 # including returning Thursday all through the weekend.
1686  
1687 # =head1 DATABASE FUNCTIONS
1688 #
1689 # =over 4
1690 #
1691 # =item C<< App::Chart::Download::write_daily_group ($hashref) >>
1692 #
1693 # C<$hashref> is daily share price data. Write it to the database. The
1694 # fields of C<$hashref> are as follows. They are variously crunched to
1695 # normalize and validate before being written to the database.
1696 #
1697 # =over
1698 #
1699 # =item C<data>
1700 #
1701 # Arrayref containing hashref records with fields
1702 #
1703 # symbol string
1704 # open price
1705 # high price
1706 # low price
1707 # close price
1708 # volume number
1709 # openint number
1710 #
1711 # Any C<symbol> not already in the database is ignored.
1712 #
1713 # =item C<dividends>
1714 #
1715 # symbol string
1716 #
1717 # Any C<symbol> not already in the database is ignored.
1718 #
1719 # =item C<splits>
1720 #
1721 # symbol string
1722 #
1723 # Any C<symbol> not already in the database is ignored.
1724 #
1725 # =item C<names>
1726 #
1727 # =item C<currencies>
1728 #
1729 # =back
1730 #
1731 #
1732 #
1733 # =item App::Chart::Download::write_latest_group ($hashref)
1734 #
1735 # ...
1736 #
1737  
1738 # =item App::Chart::Download::crunch_number ($str)
1739 #
1740 # =item App::Chart::Download::crunch_price ($price, $prefer_decimals)
1741 #
1742 # =item App::Chart::Download::crunch_change ($change, $prefer_decimals)
1743 #
1744 # ...
1745 #
1746  
1747 # =item App::Chart::Download::set_symbol_name ($symbol, $name)
1748 #
1749 # Set the company or commodity name recorded in the database for C<$symbol>,
1750 # if C<$symbol> is already in the database.
1751 #
1752 # =item App::Chart::Download::set_currency ($symbol, $currency)
1753 #
1754 # Set the currency recorded in the database for C<$symbol>, if C<$symbol> is
1755 # already in the database. C<$currency> should be a three-letter currency
1756 # code, like "GBP" for British Pounds.
1757 #
1758 # =item App::Chart::Download::set_isin ($symbol, $isin)
1759 #
1760 # Set the ISIN recorded in the database for C<$symbol>, if C<$symbol> is
1761 # already in the database.
1762 #
1763 # =item App::Chart::Download::set_decimals ($symbol, $decimals)
1764 #
1765 # Set the number of decimals to show for prices of C<$symbol>, if C<$symbol>
1766 # is already in the database.
1767 #
1768  
1769  
1770 # =item download (key=>value, ...)
1771 #
1772 # ...
1773 #
1774 # =cut
1775  
1776 # =item C<< App::Chart::Download::start_tdate_for_update ($symbol, ...) >>
1777 #
1778 # Return the tdate to start at for a data update of all the given symbols.
1779 # This is the day after existing data of the oldest, or five years ago if any
1780 # need an initial download.
1781 #
1782 # =cut
1783  
« App/Chart/Barchart.pm ↑ Summary App/Chart/DownloadHandler.pm »