Debian Codegraph @

lib/Finance/Quote/YahooWeb.pm

raw
1 # vi: set noai ic ts=4 sw=4 showmode showmatch:
2 # This program is free software: you can redistribute it and/or modify
3 # it under the terms of the GNU General Public License as published by
4 # the Free Software Foundation, either version 3 of the License, or
5 # (at your option) any later version.
6 #
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14
15 package Finance::Quote::YahooWeb;
16
17 use warnings;
18 use strict;
19
20 use Encode qw( encode_utf8 );
21 use HTTP::Request::Common;
22 use HTML::TreeBuilder::XPath;
23 use JSON qw( decode_json );
24 use LWP::Protocol::http;
25 use Text::Template;
26 use HTTP::Cookies;
27 use URI::Escape;
28
29 use constant DEBUG => $ENV{DEBUG};
30 use if DEBUG, 'Smart::Comments';
31
32 use constant URLTAG => "data-url";
33 use constant JSONBODY => "body";
34
35 our $VERSION = '1.71'; # VERSION
36
37 # Fix for 500 Header line too long message
38 push(@LWP::Protocol::http::EXTRA_SOCK_OPTS, MaxLineLength => 0);
39
40 my $URL = Text::Template->new(TYPE => 'STRING', SOURCE => 'https://finance.yahoo.com/quote/{$symbol}/history?p={$symbol}&crumb={$crumb}');
41 # my $AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36';
42 my $AGENT = 'Mozilla/5.0';
43 my $XPATH = Text::Template->new(TYPE => 'STRING', SOURCE => '//*[@data-symbol=~"^{$symbol}$"][@data-field=~"regularMarketPrice"]');
44
45 our $DISPLAY = '<Module Name + Brief Info>';
46 our @LABELS = qw/symbol name exchange currency isodate last open high low volume/;
47 our $METHODHASH = {subroutine => \&yahooweb,
48 display => $DISPLAY,
49 labels => \@LABELS};
50
51 sub methodinfo {
52 return (
53 yahooweb => $METHODHASH,
54 );
55 }
56
57 sub labels {
58 my %m = methodinfo();
59 return map {$_ => [@{$m{$_}{labels}}] } keys %m;
60 }
61
62 sub methods {
63 my %m = methodinfo(); return map {$_ => $m{$_}{subroutine} } keys %m;
64 }
65
66 sub yahooweb {
67 my $quoter = shift;
68
69 my @stocks = @_;
70 my ( %info, $url, $reply, $script_tag );
71 my $ua = $quoter->user_agent();
72 my $agent = $ua->agent();
73
74 my $cookie_jar = HTTP::Cookies->new;
75
76 # Redirect handler deals with cookie consent workflow applicable to EU countries
77 # credit to John Weber from Germany for injecting redirect handler
78 my $gcrumb = "";
79 $ua->add_handler("response_redirect", sub {
80 my($response, $ua, $h) = @_;
81
82 # Check where we've been redirected and act accordingly
83 my $redirect_uri = URI->new($response->header("Location"));
84 if ($redirect_uri->path eq "/consent") {
85
86 # Remember gcrumb value for collectConsent request later
87 my %params = $redirect_uri->query_form;
88 $gcrumb = $params{'gcrumb'};
89
90 } elsif ($redirect_uri->path eq "/v2/collectConsent") {
91
92 my %params = $redirect_uri->query_form;
93 my $sessionId = $params{'sessionId'};
94
95 # Turn this request into a POST with form data to confoo accept cookies
96 my $request = POST($redirect_uri, [
97 'csrfToken' => $gcrumb,
98 'sessionId' => $sessionId,
99 'originalDoneUrl' => 'https://www.yahoo.com/?guccounter=1',
100 'namespace' => 'yahoo',
101 # For the EU consent, either can :
102 # 'agree' => 'agree'
103 # to it or
104 'reject' => 'reject'
105 ]);
106 return $request;
107 }
108 return;
109 });
110
111 $ua->cookie_jar($cookie_jar);
112 $ua->agent($AGENT);
113
114 # Tell user agent to redirect POSTs in additional to GET AND HEAD
115 $ua->requests_redirectable(['GET', 'HEAD', 'POST']);
116
117 # get necessary cookies
118 $reply = $ua->get('https://www.yahoo.com/', "Accept" => "text/html");
119
120 if ($reply->code != 200) {
121 foreach my $symbol (@stocks) {
122 $info{$symbol, "success"} = 0;
123 $info{$symbol, "errormsg"} = "Error accessing www.yahoo.com: $@";
124 }
125 return wantarray() ? %info : \%info;
126 }
127
128 # get the crumb that corrosponds to cookies retrieved
129 $reply = $ua->request(GET 'https://query2.finance.yahoo.com/v1/test/getcrumb');
130 if ($reply->code != 200) {
131 foreach my $symbol (@stocks) {
132 $info{$symbol, "success"} = 0;
133 $info{$symbol, "errormsg"} = "Error accessing queary.finance.yahoo.com/v1/test/getcrumb: $@";
134 }
135 return wantarray() ? %info : \%info;
136 }
137 my $crumb = uri_escape($reply->content);
138
139 ### [<now>] cookie_jar : $cookie_jar
140 ### [<now>] crumb : $crumb
141
142 foreach my $symbol (@stocks) {
143 $url = $URL->fill_in(HASH => {symbol => $symbol, crumb => $crumb});
144
145 ### [<now>] YahooWeb: $url
146 $reply = $ua->request(GET $url);
147
148 ### [<now>] Reply: $reply
149
150 unless ($reply->is_success) {
151 $info{ $symbol, "success" } = 0;
152 $info{ $symbol, "errormsg" } = join ' ', $reply->code, $reply->message;
153 next;
154 }
155
156 my $tree = HTML::TreeBuilder::XPath->new();
157 $tree->ignore_unknown(0);
158 $tree->parse($reply->decoded_content);
159
160 $script_tag = $tree->look_down(_tag => 'script', type => 'application/json', URLTAG, qr!https://query1.finance.yahoo.com/v7/finance/quote\?fields=fiftyTwoWeekHigh.*! );
161
162 ### [<now>] script_tag: $script_tag
163
164 unless($script_tag) {
165 $info{ $symbol, "success" } = 0;
166 $info{ $symbol, "errormsg" } = 'Error - Symbol not found';
167 next;
168 }
169
170 my @numfound = $script_tag->content_list();
171
172 ### [<now>] numfound: @numfound
173
174 my $json_data;
175 eval {$json_data = decode_json encode_utf8( $numfound[0] )};
176 if($@) {
177 $info{ $symbol, 'success' } = 0;
178 $info{ $symbol, 'errormsg' } = $@;
179 next;
180 }
181
182 ### [<now>] json_data: $json_data
183
184 my $json_body =
185 encode_utf8($json_data->{'body'});
186 ### [<now>] json_body: $json_body;
187
188 eval {$json_data = decode_json $json_body};
189 if($@) {
190 $info{ $symbol, 'success' } = 0;
191 $info{ $symbol, 'errormsg' } = $@;
192 next;
193 }
194
195 ### [<now>] json_data 2: $json_data
196
197 my $yahoo_symbol =
198 $json_data->{'quoteResponse'}{'result'}[0]{'symbol'};
199
200 my $name = $json_data->{'quoteResponse'}{'result'}[0]{'shortName'};
201
202 if (uc($symbol) ne uc($yahoo_symbol)) {
203 ### Error: $symbol, $yahoo_symbol
204 $info{ $symbol, "success" } = 0;
205 $info{ $symbol, "errormsg" } = 'Unexpected response from Yahoo site';
206 next;
207 }
208
209 $info{ $symbol, 'name' } = $name if $name;
210 my $currency = $json_data->{'quoteResponse'}{'result'}[0]{'currency'};
211 $info{ $symbol, 'currency' } = $currency if $currency;
212 $info{ $symbol, 'exchange' } =
213 $json_data->{'quoteResponse'}{'result'}[0]{'fullExchangeName'};
214
215 if ($currency =~ /^GBp/) {
216 $info{ $symbol, 'currency' } = 'GBP';
217 } else {
218 $info{ $symbol, 'currency' } = $currency;
219 }
220
221 my $last = $json_data->{'quoteResponse'}{'result'}[0]{'regularMarketPrice'}{'fmt'};
222 $last =~ s/,//g;
223 if ($currency =~ /^GBp/) {
224 $last = $last / 100;
225 }
226
227 my $open = $json_data->{'quoteResponse'}{'result'}[0]{'regularMarketOpen'}{'fmt'};
228 if ($open) {
229 $open =~ s/,//g;
230 if ($currency =~ /^GBp/) {
231 $open = $open / 100;
232 }
233 }
234
235 my $high = $json_data->{'quoteResponse'}{'result'}[0]{'regularMarketDayHigh'}{'fmt'};
236 if ($high) {
237 $high =~ s/,//g;
238 if ($currency =~ /^GBp/) {
239 $high = $high / 100;
240 }
241 }
242
243 my $low = $json_data->{'quoteResponse'}{'result'}[0]{'regularMarketDayLow'}{'fmt'};
244 if ($low) {
245 $low =~ s/,//g;
246 if ($currency =~ /^GBp/) {
247 $low = $low / 100;
248 }
249 }
250
251 my $volume = $json_data->{'quoteResponse'}{'result'}[0]{'regularMarketVolume'}{'raw'};
252 $volume =~ s/,//g if $volume;
253
254 # regularMarketTime in JSON is seconds since epoch
255 my $tradedate = $json_data->{'quoteResponse'}{'result'}[0]{'regularMarketTime'}{'raw'};
256 my (undef,undef,undef,$day,$month,$year,undef,undef,undef) = localtime($tradedate);
257 $month += 1;
258 $year += 1900;
259
260 ### YahooWeb Result: $last
261 $info{ $symbol, 'last'} = $last;
262 $info{ $symbol, 'open'} = $open;
263 $info{ $symbol, 'high'} = $high;
264 $info{ $symbol, 'low'} = $low;
265 $info{ $symbol, 'volume'} = $volume unless $volume eq "-";
266
267 $quoter->store_date(\%info, $symbol, {month => $month, day => $day, year => $year});
268 $info{ $symbol, 'symbol' } = $symbol;
269 $info{ $symbol, 'method' } = 'yahooweb';
270 $info{ $symbol, 'success' } = 1;
271 }
272 $ua->agent($agent);
273 return wantarray ? %info : \%info;
274 }
275 1;
276
277 =head1 NAME
278
279 Finance::Quote::YahooWeb - Obtain quotes from https://finance.yahoo.com/quote
280
281 =head1 SYNOPSIS
282
283 use Finance::Quote;
284 $q = Finance::Quote->new('YahooWeb');
285 %info = $q->fetch('yahooweb', "IBM", "AAPL");
286
287 =head1 DESCRIPTION
288
289 This module fetches information from https://finance.yahoo.com/quote.
290
291 This module is loaded by default on a Finance::Quote object. It's
292 also possible to load it explicitly by placing "YahooWeb" in the argument
293 list to Finance::Quote->new().
294
295 This module provides the "yahooweb" fetch method.
296
297 =head1 LABELS RETURNED
298
299 The following labels may be returned by Finance::Quote::YahooWeb :
300 symbol name exchange currency isodate last open high low volume
301
302 =cut