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