App/Chart/Yahoo.pm

filter: Statementstmt 94.7% 36 / 38 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 13 / 13 Podpod n/a totaltotal 96.0% 49 / 51 CC 1 SCAR 0.2
CC
1
Cov
95%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« App/Chart.pm ↑ Summary App/Chart/Suffix/LME.pm »
1 # Copyright 2007, 2008, 2009, 2010, 2011, 2015, 2016, 2017, 2019, 2020 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  
18 package App::Chart::Yahoo;
19 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 1 ▶use Date::Calc;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 1 ▶use Date::Parse;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 1 ▶use List::Util qw (min max);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 1 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
27 1 ▶use Time::Local;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 1 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 1 ▶use Locale::TextDomain ('App-Chart');
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 1 ▶use Tie::TZ;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 1 ▶use App::Chart;
Subroutine BEGIN: called CC=1 SCAR=2.6
33 use App::Chart::Database;
34 use App::Chart::Download;
35 use App::Chart::DownloadHandler;
36 use App::Chart::DownloadHandler::IndivChunks;
37 use App::Chart::IntradayHandler;
38 use App::Chart::Latest;
39 use App::Chart::Sympred;
40 use App::Chart::TZ;
41 use App::Chart::Weblink;
42  
43 # uncomment this to run the ### lines
44 # use Smart::Comments;
45  
46 use constant DEBUG => 0;
47  
48  
49 # .X or .XY or no suffix
50 our $yahoo_pred = App::Chart::Sympred::Proc->new
51 (sub {
52 my ($symbol) = @_;
53 return ($symbol !~ /\.(FQ|LJ)$/
54 && $symbol =~ /[.=]..?$|^[^.]+$/);
55 });
56  
57 my $download_pred = App::Chart::Sympred::Any->new ($yahoo_pred);
58 our $latest_pred = App::Chart::Sympred::Any->new ($yahoo_pred);
59 our $index_pred = App::Chart::Sympred::Regexp->new (qr/^\^|^0.*\.SS$/);
60 my $futures_pred = App::Chart::Sympred::Any->new;
61  
62 # max symbols to any /q? quotes request
63 # Finance::Quote::Yahoo uses a limit of 40 to stop the url getting too
64 # long, which apparently some servers or proxies can't handle
65 use constant MAX_QUOTES => 40;
66  
67 # overridden by specific nodes
68 App::Chart::setup_source_help
69 ($yahoo_pred, __p('manual-node','Yahoo Finance'));
70  
71  
72 #-----------------------------------------------------------------------------
73 # web link - basic quote page
74 #
75 # Eg. http://finance.yahoo.com/q?s=BHP.AX
76 #
77 # The accelerator is "_Y" so as not to clash with "_S" for stock on various
78 # stock exchange links like "ASX IRM _Stock Information"
79  
80 App::Chart::Weblink->new
81 (pred => $yahoo_pred,
82 name => __('_Yahoo Stock Page'),
83 desc => __('Open web browser at the Yahoo quote page for this stock'),
84 proc => sub {
85 my ($symbol) = @_;
86 return "http://"
87 . App::Chart::Database->preference_get ('yahoo-quote-host',
88 'finance.yahoo.com')
89 . "/q?s="
90 . URI::Escape::uri_escape($symbol);
91 });
92  
93  
94 #-----------------------------------------------------------------------------
95 # misc
96  
97  
98 # (if (and (yahoo-futures-symbol? symbol)
99 # (not (chart-symbol-mdate symbol)))
100 # (let* ((want-tdate (adate->tdate
101 # (first
102 # (yahoo-quote-adate-time symbol ""))))
103 # (mdate (or (latest-symbol-mdate-nodownload symbol
104 # want-tdate)
105 # (begin
106 # (weblink-message
107 # (_ "Finding front month ..."))
108 # (latest-symbol-mdate symbol want-tdate)))))
109 # (if mdate # might still be unknown
110 # (set! symbol
111 # (string-append (chart-symbol-commodity symbol)
112 # (mdate->MYY-str mdate)
113 # (chart-symbol-suffix symbol))))))
114  
115  
116 #-----------------------------------------------------------------------------
117 # Exchanges page for quote delays
118 #
119 # This looks at the exchanges page
120 #
121 use constant EXCHANGES_URL => 'https://help.yahoo.com/kb/SLN2310.html';
122  
123 # Exchanges page was previously http://finance.yahoo.com/exchanges, but why
124 # would they keep it the same when breaking everybody's links would be
125 # better.
126  
127 # refetch the exchanges page after this many days
128 use constant EXCHANGES_UPDATE_DAYS => 7;
129  
130 # containing arefs [$pred,'.XX']
131 my @quote_delay_aliases;
132  
133 sub setup_quote_delay_alias {
134 my ($pred, $suffix) = @_;
135 push @quote_delay_aliases, [ $pred, $suffix ];
136 }
137  
138 sub symbol_quote_delay {
139 my ($symbol) = @_;
140  
141 # indexes all in real time
142 if ($index_pred->match($symbol)) {
143 return 0;
144 }
145  
146 my $suffix = App::Chart::symbol_suffix ($symbol);
147 my $h = exchanges_data();
148 my $delay = $h->{$suffix};
149  
150 if (! defined $delay) {
151 if (my $elem = List::Util::first { $_->[0]->match ($symbol) }
152 @quote_delay_aliases) {
153 $suffix = $elem->[1];
154 $delay = $h->{$suffix};
155 }
156 }
157 if (! defined $delay) {
158 # guess default 20 minutes
159 $delay = 20;
160 }
161 return $delay;
162 }
163  
164 # return a hashref of exchange delay data like { '.AX' => 20, '.BI' => 15 }
165 sub exchanges_data {
166 require App::Chart::Pagebits;
167 return App::Chart::Pagebits::get
168 (name => __('Yahoo exchanges page'),
169 url => EXCHANGES_URL,
170 key => 'yahoo-quote-delays',
171 freq_days => EXCHANGES_UPDATE_DAYS,
172 parse => \&exchanges_parse);
173 }
174 sub exchanges_parse {
175 my ($content) = @_;
176 my $h = {};
177  
178 require HTML::TableExtract;
179 my $te = HTML::TableExtract->new (headers => ['Suffix', 'Delay']);
180 $te->parse($content);
181 if (! $te->tables) {
182 warn "Yahoo exchanges page unrecognised, assuming 15 min quote delay";
183 return $h;
184 }
185  
186 foreach my $row ($te->rows) {
187 my $suffix = $row->[0];
188 my $delay = $row->[1];
189 next if ($suffix eq 'N/A');
190  
191 # eg "15 min"
192 # or "15 min**" with footnote
193 #
194 if ($delay =~ /^(\d+) min/) {
195 $delay = $1;
196 } elsif ($delay =~ /real/i) {
197 $delay = 0;
198 } else {
199 warn "Yahoo exchanges page unrecognised delay: \"$delay\"\n";
200 next;
201 }
202  
203 $h->{$suffix} = $delay + 0;
204 }
205 return $h;
206 }
207  
208  
209 #------------------------------------------------------------------------------
210 # latest
211 #
212 # https://stackoverflow.com/questions/47076404/currency-helper-of-yahoo-sorry-unable-to-process-request-at-this-time-erro
213 # ->
214 # https://stackoverflow.com/questions/47064776/has-yahoo-suddenly-today-terminated-its-finance-download-api
215  
216 App::Chart::LatestHandler->new
217 (pred => $latest_pred,
218 proc => \&latest_download,
219 max_symbols => 1); # downloads go 1 at a time
220  
221 sub latest_download {
222 my ($symbol_list) = @_;
223  
224 foreach my $symbol (@$symbol_list) {
225 my $tdate = daily_available_tdate ($symbol);
226 App::Chart::Download::status(__('Yahoo quote'), $symbol);
227  
228 my $lo_timet = tdate_to_unix($tdate - 4);
229 my $hi_timet = tdate_to_unix($tdate + 2);
230  
231 my $events = 'history';
232 my $url = "https://query1.finance.yahoo.com/v7/finance/chart/"
233 . URI::Escape::uri_escape($symbol)
234 ."?period1=$lo_timet&period2=$hi_timet&interval=1d&events=$events";
235  
236 # unknown symbol is 404 with json error details
237 #
238 my $resp = App::Chart::Download->get ($url, allow_404 => 1,);
239 App::Chart::Download::write_latest_group
240 (latest_parse($symbol,$resp,$tdate));
241 }
242 }
243  
244 sub latest_parse {
245 my ($symbol, $resp, $tdate) = @_;
246  
247 my $content = $resp->decoded_content (raise_error => 1);
248 require JSON;
249 my $json = JSON::from_json($content);
250  
251 my %record = (symbol => $symbol,
252 );
253 my $h = { source => __PACKAGE__,
254 resp => $resp,
255 prefer_decimals => 2,
256 date_format => 'ymd',
257 data => [ \%record ],
258 };
259 if (defined (my $error = $json->{'chart'}->{'error'}->{'code'})) {
260 $record{'error'} = $error;
261 }
262  
263 if (my $result = $json->{'chart'}->{'result'}->[0]) {
264 my $meta = $result->{'meta'}
265 // die "Yahoo JSON oops, no meta";
266 $record{'currency'} = $meta->{'currency'},
267 $record{'exchange'} = $meta->{'exchangeName'},
268  
269 my $symbol_timezone = App::Chart::TZ->for_symbol ($symbol);
270 my $timestamps = $result->{'timestamp'}
271 // die "Yahoo JSON oops, no timestamp";
272  
273 if (@$timestamps) {
274  
275 # timestamps are time of last trade, as can be seen by looking at
276 # something with low enough volume, eg. RMX.AX
277 #
278 if (defined (my $timet = $timestamps->[-1])) {
279 ($record{'last_date'}, $record{'last_time'})
280 = $symbol_timezone->iso_date_time($timet);
281 }
282  
283 if (my $indicators = $result->{'indicators'}->{'quote'}->[0]) {
284 foreach my $key ('open','high','low') {
285 if (my $aref = $indicators->{$key}) {
286 $record{$key} = crunch_trailing_nines($aref->[$#$timestamps]);
287 }
288 }
289 if (my $aref = $indicators->{'volume'}) {
290 $record{'volume'} = $aref->[$#$timestamps];
291 }
292 if (my $aref = $indicators->{'close'}) {
293 my $last = $record{'last'}
294 = crunch_trailing_nines($aref->[$#$timestamps]);
295  
296 # "change" from second last timestamp, if there is one.
297 # As of Nov 17, XAUUSD=X only ever gives a single latest quote
298 # from v7, no previous day to compare.
299 #
300 if (defined $last
301 && scalar(@$timestamps) >= 2
302 && defined(my $prev = $aref->[$#$timestamps - 1])) {
303 $record{'change'}
304 = App::Chart::decimal_sub($last, crunch_trailing_nines($prev));
305 }
306 }
307 }
308 }
309  
310 if (defined $record{'last_date'}
311 && (my $splits = $result->{'events'}->{'splits'})) {
312 while (my ($timet, $href) = each %$splits) {
313 my $split_date = $symbol_timezone->iso_date($timet);
314 if ($split_date eq $record{'last_date'}) {
315 __x('Split {ratio}', ratio => $href->{'splitRatio'})
316 }
317 }
318 }
319 }
320 return $h;
321 }
322  
323  
324 #-----------------------------------------------------------------------------
325 # download
326 #
327 # This uses the historical prices page like
328 #
329 # https://finance.yahoo.com/quote/AMP.AX/history?p=AMP.AX
330 #
331 # which puts a cookie like
332 #
333 # Set-Cookie: B=fab5sl9cqn2rd&b=3&s=i3; expires=Sun, 03-Sep-2018 04:56:13 GMT; path=/; domain=.yahoo.com
334 #
335 # and contains buried within a mountain of hideous script
336 #
337 # "CrumbStore":{"crumb":"hdDX\u002FHGsZ0Q"}
338 #
339 # The \u002F is backslash character (etc) which is script string for "/"
340 # character. The crumb is included in a CSV download query like (alas can't
341 # use http, it redirects to https)
342 #
343 # https://query1.finance.yahoo.com/v7/finance/download/AMP.AX?period1=1503810440&period2=1504415240&interval=1d&events=history&crumb=hdDX/HGsZ0Q
344 #
345 # period1 is the start time, period2 the end time, both as Unix seconds
346 # since 1 Jan 1970. Not sure of the timezone needed. Some experiments
347 # suggest it depends on the timezone of the symbol. http works as well as
348 # https. The result is like
349 #
350 # Date,Open,High,Low,Close,Adj Close,Volume
351 # 2017-09-07,30.299999,30.379999,30.000000,30.170000,30.170000,3451099
352 #
353 # The "9999s" are some bad rounding off to what would be usually at most
354 # 3 (maybe 4?) decimal places.
355 #
356 # Response is 404 if no such symbol, 401 unauthorized if no cookie or crumb.
357 #
358 # "events=div" gives dividends like
359 #
360 # Date,Dividends
361 # 2017-08-11,0.161556
362 #
363 # "events=div" gives splits like, for a consolidation (GXY.AX)
364 #
365 # Date,Stock Splits
366 # 2017-05-22,1/5
367 #
368 #----------------
369 # For reference, there's a similar further which is json format (%7C = "|")
370 #
371 # https://query2.finance.yahoo.com/v8/finance/chart/IBM?formatted=true&lang=en-US&region=US&period1=1504028419&period2=1504428419&interval=1d&events=div%7Csplit&corsDomain=finance.yahoo.com
372 #
373 # This doesn't require a cookie and crumb, has some info like symbol
374 # timezone. The numbers look like they're rounded through 32-bit floating
375 # point, for example "142.55999755859375" which is 142.55 in a 23-bit
376 # mantissa. log(14255000)/log(2) = 23.76 bits
377 #
378 # FIXME: All prices look like they are split-adjusted, which is ok if that's
379 # what you want and are downloading a full data set, but bad for incremental
380 # since you don't know when a change is applied.
381 #
382  
383 App::Chart::DownloadHandler->new
384 (name => __('Yahoo'),
385 pred => $download_pred,
386 available_tdate_by_symbol => \&daily_available_tdate,
387 available_tdate_extra => 2,
388 url_and_cookiejar_func => \&daily_url_and_cookiejar,
389 proc => \&daily_download,
390 chunk_size => 150);
391  
392 sub daily_available_tdate {
393 my ($symbol) = @_;
394  
395 # Sep 2017: daily data is present for the current day's trade, during the
396 # trading session. Try reckoning it complete at 6pm.
397 return App::Chart::Download::tdate_today_after
398 (18,0, App::Chart::TZ->for_symbol ($symbol));
399  
400 # return App::Chart::Download::tdate_today_after
401 # (10,30, App::Chart::TZ->for_symbol ($symbol))
402 # - 1;
403 }
404  
405 sub daily_download {
406 my ($symbol_list) = @_;
407 App::Chart::Download::status (__('Yahoo daily data'));
408  
409 # App::Chart::Download::verbose_message ("Yahoo crumb $crumb cookies\n"
410 # . $jar->as_string);
411  
412 my $crumb_errors = 0;
413 SYMBOL: foreach my $symbol (@$symbol_list) {
414 my $lo_tdate = App::Chart::Download::start_tdate_for_update (@$symbol_list);
415 my $hi_tdate = daily_available_tdate ($symbol);
416  
417 App::Chart::Download::status
418 (__('Yahoo data'), $symbol,
419 App::Chart::Download::tdate_range_string ($lo_tdate, $hi_tdate));
420  
421 my $lo_timet = tdate_to_unix($lo_tdate - 2);
422 my $hi_timet = tdate_to_unix($hi_tdate + 2);
423  
424 my $data = daily_cookie_data($symbol);
425 if (! defined $data) {
426 print "Yahoo $symbol does not exist\n";
427 next SYMBOL;
428 }
429 my $crumb = URI::Escape::uri_escape($data->{'crumb'});
430 my $jar = http_cookies_from_string($data->{'cookies'} // '');
431  
432 my $h = { source => __PACKAGE__,
433 prefer_decimals => 2,
434 date_format => 'ymd',
435 };
436 foreach my $elem (['history',\&daily_parse],
437 ['div', \&daily_parse_div],
438 ['split', \&daily_parse_split]) {
439 my ($events,$parse) = @$elem;
440 my $url = "https://query1.finance.yahoo.com/v7/finance/download/"
441 . URI::Escape::uri_escape($symbol)
442 . "?period1=$lo_timet&period2=$hi_timet&interval=1d&events=$events&crumb=$crumb";
443  
444 my $resp = App::Chart::Download->get ($url,
445 allow_401 => 1,
446 allow_404 => 1,
447 cookie_jar => $jar,
448 );
449 if ($resp->code == 401) {
450 if (++$crumb_errors >= 2) { die "Yahoo: crumb authorization failed"; }
451 App::Chart::Database->write_extra ('', 'yahoo-daily-cookies', undef);
452 redo SYMBOL;
453 }
454 if ($resp->code == 404) {
455 print "Yahoo $symbol does not exist\n";
456 next SYMBOL;
457 }
458 $parse->($symbol,$resp,$h, $hi_tdate);
459 }
460 ### $h
461 App::Chart::Download::write_daily_group ($h);
462 }
463 }
464  
465 sub daily_parse {
466 my ($symbol, $resp, $h, $hi_tdate) = @_;
467 my @data = ();
468 $h->{'data'} = \@data;
469 my $hi_tdate_iso;
470 if (defined $hi_tdate){ $hi_tdate_iso = App::Chart::tdate_to_iso($hi_tdate); }
471  
472 my $body = $resp->decoded_content (raise_error => 1);
473 my @line_list = App::Chart::Download::split_lines($body);
474  
475 unless ($line_list[0] =~ /^Date,Open,High,Low,Close,Adj Close,Volume/) {
476 die "Yahoo: unrecognised daily data headings: " . $line_list[0];
477 }
478 shift @line_list;
479  
480 foreach my $line (@line_list) {
481 my ($date, $open, $high, $low, $close, $adj_volume, $volume)
482 = split (/,/, $line);
483  
484 $date = daily_date_fixup ($symbol, $date);
485 if (defined $hi_tdate_iso && $date gt $hi_tdate_iso) {
486 # Sep 2017: There's a daily data record during the trading day, but
487 # want to write the database only at the end of trading.
488 ### skip date after hi_tdate ...
489 next;
490 }
491  
492 # Sep 2017 have seen "null,null,null,...", maybe for non-trading days
493 foreach my $field ($open, $high, $low, $close, $adj_volume, $volume) {
494 if ($field eq 'null') {
495 $field = undef;
496 }
497 }
498  
499 if ($index_pred->match($symbol)) {
500 # In the past indexes which not calculated intraday had
501 # open==high==low==close and volume==0, eg. ^WIL5. Use the close
502 # alone in this case, with the effect of drawing line segments instead
503 # of OHLC or Candle figures with no range.
504  
505 if (defined $open && defined $high && defined $low && defined $close
506 && $open == $high && $high == $low && $low == $close && $volume == 0){
507 $open = undef;
508 $high = undef;
509 $low = undef;
510 }
511  
512 } else {
513 # In the past shares with no trades had volume==0,
514 # open==low==close==bid price, and high==offer price, from some time
515 # during the day, maybe the end of day. Zap all the prices in this
516 # case.
517 #
518 # For a public holiday it might be good to zap the volume to undef
519 # too, but don't have anything to distinguish holiday, suspension,
520 # delisting vs just no trades.
521 #
522 # On the ASX when shares are suspended the bid/offer can be crossed as
523 # usual for pre-open auction, and this gives high<low. For a part-day
524 # suspension then can have volume!=0 in this case too. Don't want to
525 # show a high<low, so massage high/low to open/close range if the high
526 # looks like a crossed offer.
527  
528 if (defined $high && defined $low && $high < $low) {
529 $high = App::Chart::max_maybe ($open, $close);
530 $low = App::Chart::min_maybe ($open, $close);
531 }
532  
533 if (defined $open && defined $low && defined $close && defined $volume
534 && $open == $low && $low == $close && $volume == 0) {
535 $open = undef;
536 $high = undef;
537 $low = undef;
538 $close = undef;
539 }
540 }
541  
542 push @data, { symbol => $symbol,
543 date => $date,
544 open => crunch_trailing_nines($open),
545 high => crunch_trailing_nines($high),
546 low => crunch_trailing_nines($low),
547 close => crunch_trailing_nines($close),
548 volume => $volume };
549 }
550 return $h;
551 }
552 sub daily_parse_div {
553 my ($symbol, $resp, $h) = @_;
554 my @dividends = ();
555 $h->{'dividends'} = \@dividends;
556  
557 my $body = $resp->decoded_content (raise_error => 1);
558 my @line_list = App::Chart::Download::split_lines($body);
559  
560 # Date,Dividends
561 # 2015-11-04,1.4143
562 # 2016-05-17,1.41428
563 # 2017-05-16,1.4143
564 # 2016-11-03,1.4143
565  
566 unless ($line_list[0] =~ /^Date,Dividends/) {
567 warn "Yahoo: unrecognised dividend headings: " . $line_list[0];
568 return;
569 }
570 shift @line_list;
571  
572 foreach my $line (@line_list) {
573 my ($date, $amount) = split (/,/, $line);
574  
575 push @dividends, { symbol => $symbol,
576 ex_date => daily_date_fixup ($symbol, $date),
577 amount => $amount };
578 }
579 return $h;
580 }
581 sub daily_parse_split {
582 my ($symbol, $resp, $h) = @_;
583 my @splits = ();
584 $h->{'splits'} = \@splits;
585  
586 my $body = $resp->decoded_content (raise_error => 1);
587 my @line_list = App::Chart::Download::split_lines($body);
588  
589 # For example GXY.AX split so $10 shares become $2
590 # Date,Stock Splits
591 # 2017-05-22,1:5
592 #
593 # In the past it was a "/" instad of ":"
594 # 2017-05-22,1/5
595  
596 unless ($line_list[0] =~ /^Date,Stock Splits/) {
597 warn "Yahoo: unrecognised split headings: " . $line_list[0];
598 return;
599 }
600 shift @line_list;
601  
602 foreach my $line (@line_list) {
603 my ($date, $ratio) = split (/,/, $line);
604 my ($old, $new) = split m{[:/]}, $ratio;
605  
606 push @splits, { symbol => $symbol,
607 date => daily_date_fixup ($symbol, $date),
608 new => $new,
609 old => $old };
610 }
611 return $h;
612 }
613  
614 # ENHANCE-ME: The digits are 23-bit float formatted badly, or so it seems.
615 # That makes it 23 / (log(10)/log(2)) = 6.92 many high digits good.
616  
617 # Maybe round-to-nearest of high 7 digits, or maybe only high 6 depending
618 # where the bit range falls (how many bits used by the high digit).
619 #
620 # $str is a string like "30.299999"
621 # Return it with trailing 9s turned into trailing 0s.
622 sub crunch_trailing_nines {
623 my ($str) = @_;
624 if (defined $str) {
625 $str =~ s/(\....(99|00)).*/$1/; # trailing garbage
626  
627 if ($str =~ /(.*)\.(....9+)$/) {
628 $str = decimal_add_low($str,1);
629 } elsif ($str =~ /(.*)\.(....*01)$/) {
630 $str = decimal_add_low($str,-1);
631 }
632  
633 if ($str =~ /(.*)\./) {
634 my $ilen = length($1);
635 my $decimals = ($ilen >= 4 ? 2
636 : $ilen == 3 ? 3
637 : 4);
638 $str = round_decimals($str,$decimals);
639 }
640 $str = pad_decimals($str, 2);
641 }
642 return $str;
643 }
644 sub decimal_add_low {
645 my ($str, $add) = @_;
646 ### decimal_add_low(): "$str $add"
647 $str =~ /(.*)\.(.+)$/ or return $str+$add;
648 my $pre = $1;
649 my $post = $2;
650 ### $pre
651 ### $post
652 $str = $pre * 10**length($post) + $post + $add;
653 if (length($post) >= length($str)) { $str = '0'.$str; }
654 substr($str, -length($post),0, '.');
655 return $str;
656 }
657 sub round_decimals {
658 my ($str, $decimals) = @_;
659 if (defined $str && $str =~ /(.*\.[0-9]{$decimals})([0-9])/) {
660 $str = $1;
661 if ($2 >= 5) { $str = decimal_add_low($str, 1); }
662 }
663 return $str;
664 }
665 sub pad_decimals {
666 my ($str, $decimals) = @_;
667 ### pad_decimals(): "$str $decimals"
668 my $got;
669 if ($str =~ /\.(.*)/) {
670 $got = length($1);
671 } else {
672 $got = 0;
673 $str .= '.';
674 }
675 if ((my $add = $decimals - $got) > 0) {
676 $str .= '0' x $add;
677 }
678 return $str;
679 }
680  
681 # return a hashref
682 # { cookies => string, # in format HTTP::Cookies ->as_string()
683 # crumb => string
684 # }
685 #
686 # If no such $symbol then return undef;
687 #
688 # Any $symbol which exists is good enough to get a crumb for all later use.
689 # Could hard-code something likely here, but better to go from the symbol
690 # which is wanted.
691 #
692 sub daily_cookie_data {
693 my ($symbol) = @_;
694 require App::Chart::Pagebits;
695 $symbol = URI::Escape::uri_escape($symbol);
696 return App::Chart::Pagebits::get
697 (name => __('Yahoo daily cookie'),
698 url => "https://finance.yahoo.com/quote/$symbol/history?p=$symbol",
699 key => 'yahoo-daily-cookies',
700 freq_days => 3,
701 parse => \&daily_cookie_parse,
702 allow_404 => 1);
703 }
704 sub daily_cookie_parse {
705 my ($content, $resp) = @_;
706  
707 # script like, with backslash escaping on "\uXXXX"
708 #"CrumbStore":{"crumb":"hdDX\u002FHGsZ0Q"}
709 #
710 $content =~ /"CrumbStore":\{"crumb":"([^"]*)"}/
711 or die "Yahoo daily data: CrumbStore not found";
712 my $crumb = App::Chart::Yahoo::javascript_string_unquote($1);
713  
714 # header like
715 # Set-Cookie: B=fab5sl9cqn2rd&b=3&s=i3; expires=Sun, 03-Sep-2018 04:56:13 GMT; path=/; domain=.yahoo.com
716 #
717 # Expiry time is +1 year, but dunno if would really work that long.
718 #
719 require HTTP::Cookies;
720 my $jar = HTTP::Cookies->new;
721 $jar->extract_cookies($resp);
722 my $cookies_str = $jar->as_string;
723  
724 App::Chart::Download::verbose_message ("Yahoo new crumb $crumb\n"
725 . $cookies_str);
726 return { crumb => $crumb,
727 cookies => $cookies_str };
728 }
729  
730 # $str is an ISO date string like 2017-11-05
731 # It is date GMT of 9:30am in the timezone of $symbol.
732 # Return the date in the symbol timezone.
733 #
734 sub daily_date_fixup {
735 my ($symbol, $str) = @_;
736 ### daily_date_fixup: "$symbol $str"
737 my ($year, $month, $day) = App::Chart::iso_to_ymd ($str);
738  
739 my $timezone = App::Chart::TZ->for_symbol($symbol);
740 if (timezone_gmtoffset_at_ymd($timezone, $year, $month, $day+1)
741 <= - (10*60+20)*60) {
742 my $adate = App::Chart::ymd_to_adate ($year, $month, $day);
743 $str = App::Chart::adate_to_iso ($adate+1);
744 my $today = $timezone->iso_date();
745 if ($str gt $today) {
746 $str = $today;
747 }
748 }
749 return $str;
750 }
751  
752 sub timezone_gmtoffset_at_ymd {
753 my ($timezone, $year, $month, $day) = @_;
754 my $timet = $timezone->call(\&POSIX::mktime,
755 0, 0, 0, $day, $month-1, $year-1900);
756 my ($sec,$min,$hour,$gmt_day) = gmtime($timet);
757 return $sec + 60*$min + 3600*$hour + 86400*($gmt_day - $day);
758 }
759  
760 # Return seconds since 00:00:00, 1 Jan 1970 GMT.
761 sub tdate_to_unix {
762 my ($tdate) = @_;
763 my $adate = App::Chart::tdate_to_adate ($tdate);
764 return ($adate + 4)*86400;
765 }
766  
767 # $str is a string from previous HTTP::Cookies ->as_string()
768 # Return a new HTTP::Cookies object with that content.
769 sub http_cookies_from_string {
770 my ($str) = @_;
771 require File::Temp;
772 my $fh = File::Temp->new (TEMPLATE => 'chart-XXXXXX',
773 TMPDIR => 1);
774 print $fh "#LWP-Cookies-1.0\n", $str or die;
775 close $fh or die;
776 require HTTP::Cookies;
777 my $jar = HTTP::Cookies->new;
778 $jar->load($fh->filename);
779 return $jar;
780 }
781  
782  
783 #-----------------------------------------------------------------------------
784 # stock info
785 #
786 # Eg. http://download.finance.yahoo.com/d?f=snxc4qr1d&s=TLS.AX
787  
788 # App::Chart::DownloadHandler->new
789 # (name => __('Yahoo info'),
790 # key => 'Yahoo-info',
791 # pred => $download_pred,
792 # proc => \&info_download,
793 # recheck_days => 7,
794 # max_symbols => MAX_QUOTES);
795 #
796 # sub info_download {
797 # my ($symbol_list) = @_;
798 #
799 # App::Chart::Download::status
800 # (__x('Yahoo info {symbolrange}',
801 # symbolrange =>
802 # App::Chart::Download::symbol_range_string ($symbol_list)));
803 #
804 # my $url = 'http://download.finance.yahoo.com/d?f=snxc4qr1d&s='
805 # . join (',', map { URI::Escape::uri_escape($_) } @$symbol_list);
806 # my $resp = App::Chart::Download->get ($url);
807 # my $h = info_parse($resp);
808 # $h->{'recheck_list'} = $symbol_list;
809 # App::Chart::Download::write_daily_group ($h);
810 # }
811 #
812 # sub info_parse {
813 # my ($resp) = @_;
814 #
815 # my $content = $resp->decoded_content (raise_error => 1);
816 # if (DEBUG >= 2) { print "Yahoo info:\n$content\n"; }
817 #
818 # my @info;
819 # my @dividends;
820 # my $h = { source => __PACKAGE__,
821 # info => \@info,
822 # dividends => \@dividends };
823 #
824 # require Text::CSV_XS;
825 # my $csv = Text::CSV_XS->new;
826 #
827 # foreach my $line (App::Chart::Download::split_lines ($content)) {
828 # $csv->parse($line);
829 # my ($symbol, $name, $exchange, $currency, $ex_date, $pay_date, $amount)
830 # = $csv->fields();
831 #
832 # $ex_date = quote_parse_div_date ($ex_date);
833 # $pay_date = quote_parse_div_date ($pay_date);
834 #
835 # push @info, { symbol => $symbol,
836 # name => $name,
837 # currency => $currency,
838 # exchange => $exchange };
839 # # circa 2015 the "d" dividend amount field is "N/A" when after the
840 # # dividend payment (with "r1" pay date "N/A" too)
841 # if ($ex_date && $amount ne 'N/A' && $amount != 0) {
842 # push @dividends, { symbol => $symbol,
843 # ex_date => $ex_date,
844 # pay_date => $pay_date,
845 # amount => $amount };
846 # }
847 # }
848 # return $h;
849 # }
850  
851  
852 #------------------------------------------------------------------------------
853 # undo javascript string backslash quoting in STR, per
854 #
855 # https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#String_Literals
856 #
857 # Encode::JavaScript::UCS does \u, but not the rest
858 #
859 # cf Java as such not quite the same:
860 # unicode: http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#100850
861 # strings: http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089
862 #
863 my %javascript_backslash = ('b' => "\b", # backspace
864 'f' => "\f", # formfeed
865 'n' => "\n", # newline
866 'r' => "\r",
867 't' => "\t", # tab
868 'v' => "\013", # vertical tab
869 );
870 sub javascript_string_unquote {
871 my ($str) = @_;
872 $str =~ s{\\(?:
873 ((?:[0-3]?[0-7])?[0-7]) # $1 \377 octal latin-1
874 |x([0-9a-fA-F]{2}) # $2 \xFF hex latin-1
875 |u([0-9a-fA-F]{4}) # $3 \uFFFF hex unicode
876 |(.) # $4 \n etc escapes
877 )
878 }{
879 (defined $1 ? chr(oct($1))
880 : defined $4 ? ($javascript_backslash{$4} || $4)
881 : chr(hex($2||$3))) # \x,\u hex
882 }egx;
883 return $str;
884 }
885  
886 #------------------------------------------------------------------------------
887 1;
888 __END__
« App/Chart.pm ↑ Summary App/Chart/Suffix/LME.pm »