Debian Codegraph @

lib/Finance/Quote/MarketWatch.pm

raw
1 #!/usr/bin/perl -w
2 # vi: set ts=2 sw=2 noai ic showmode showmatch:
3 #
4 # Copyright (C) 2023, Bruce Schuck <[email protected]>
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 # 02110-1301, USA
20 #
21
22 package Finance::Quote::MarketWatch;
23
24 use strict;
25 use warnings;
26
27 use Encode qw(decode);
28 use HTTP::Request::Common;
29 use HTML::TreeBuilder;
30
31 use constant DEBUG => $ENV{DEBUG};
32 use if DEBUG, 'Smart::Comments', '###';
33
34 our $VERSION = '1.71'; # VERSION
35
36 our $DISPLAY = 'MarketWatch';
37 our $FEATURES = {};
38 our @LABELS = qw/symbol name last date currency method/;
39 our $METHODHASH = {subroutine => \&marketwatch,
40 display => $DISPLAY,
41 labels => \@LABELS,
42 features => $FEATURES};
43
44 sub methodinfo {
45 return (
46 marketwatch => $METHODHASH,
47 nyse => $METHODHASH,
48 nasdaq => $METHODHASH,
49 );
50 }
51
52 sub methods {
53 my %m = methodinfo();
54 return map {$_ => $m{$_}{subroutine} } keys %m;
55 }
56
57 sub labels {
58 my %m = methodinfo();
59 return map {$_ => [@{$m{$_}{labels}}] } keys %m;
60 }
61
62 my $MW_URL = 'https://www.marketwatch.com/investing/stock/';
63
64 sub marketwatch {
65
66 my $quoter = shift;
67 my @stocks = @_;
68 my (%info, $tree, $url, $reply);
69 my $ua = $quoter->user_agent();
70
71 $ua->agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36");
72
73 my @ua_headers = (
74 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
75 'Accept-Language' => 'en-US,en;q=0.9',
76 'Accept-Encoding' => 'gzip, deflate, br',
77 'Connection' => 'keep-alive',
78 'Upgrade-Insecure-Requests' => '1',
79 'Sec-Fetch-Dest' => 'document',
80 'Sec-Fetch-Mode' => 'navigate',
81 'Sec-Fetch-Site' => 'none',
82 'Sec-Fetch-User' => '?1',
83 );
84
85 # Enable cookie handling (websites often check if you can store cookies)
86 $ua->cookie_jar({});
87
88 foreach my $stock (@stocks) {
89
90 $url = $MW_URL . $stock;
91 $reply = $ua->get($url, @ua_headers);
92
93 my $code = $reply->code;
94 my $desc = HTTP::Status::status_message($code);
95 my $headers = $reply->headers_as_string;
96 my $body = $reply->decoded_content;
97
98 ### Body: $body
99
100 my ($name, $last, $open, $date, $currency, $metatag);
101 my (%datehash, @timearray, $timestring);
102
103 $info{ $stock, "symbol" } = $stock;
104
105 if ( $code == 200 ) {
106
107 # Use HTML::TreeBuilder to parse HTML in $body
108 $tree = HTML::TreeBuilder->new;
109 if ($tree->parse($body)) {
110
111 $tree->eof;
112
113 if ($metatag = $tree->look_down(_tag => 'meta', name => 'name')) {
114 $info{ $stock, 'name' } = $metatag->attr('content');
115 } else {
116 $info{ $stock, 'success'} = 0;
117 $info{ $stock, 'errormsg' } = 'Error retrieving quote for $stock.';
118 next;
119 }
120
121 $metatag = $tree->look_down(_tag => 'meta', name => 'tickerSymbol');
122 $info{ $stock, 'symbol' } = $metatag->attr('content');
123
124 $metatag = $tree->look_down(_tag => 'meta', name => 'price');
125 ($info{ $stock, 'last' } = $metatag->attr('content')) =~ s/[^0-9.]//g;
126
127 $metatag = $tree->look_down(_tag => 'meta', name => 'priceCurrency');
128 $info{ $stock, 'currency' } = $metatag->attr('content');
129
130 $metatag = $tree->look_down(_tag => 'meta', name => 'quoteTime');
131 $date = $metatag->attr('content');
132 @timearray = split / /, $date;
133 $timearray[1] =~ s/[^0-9]//g;
134 %datehash = (
135 year => $timearray[2],
136 month => $timearray[0],
137 day => $timearray[1] );
138 ($timestring = $timearray[4]) =~ s|\.||g;
139 $quoter->store_date(\%info, $stock, \%datehash);
140
141 $info{ $stock, 'success' } = 1;
142
143 $info{ $stock, 'method' } = 'marketwatch';
144
145 } else {
146 $tree->eof;
147 $info{ $stock, "success" } = 0;
148 $info{ $stock, "errormsg" } =
149 "Error retrieving quote for $stock. Could not parse HTML returned from $url.";
150 }
151
152 } else { # HTTP Request failed (code != 200)
153 $info{ $stock, "success" } = 0;
154 $info{ $stock, "errormsg" } =
155 "Error retrieving quote for $stock. Attempt to fetch the URL $url resulted in HTTP response $code ($desc)";
156 }
157
158 }
159
160 return wantarray() ? %info : \%info;
161 return \%info;
162
163 }
164
165 1;
166
167 __END__
168
169 =head1 NAME
170
171 Finance::Quote::MarketWatch - Obtain quotes from MarketWatch Website
172
173 =head1 SYNOPSIS
174
175 use Finance::Quote;
176
177 $q = Finance::Quote->new;
178
179 %info = $q->fetch("marketwatch", "aapl"); # Only query marketwatch
180
181 %info = $q->fetch("nyse", "f"); # Failover to other sources OK.
182
183 =head1 DESCRIPTION
184
185 This module fetches information from L<https://www.marketwatch.com/>.
186
187 This module is loaded by default on a Finance::Quote object. It's also possible
188 to load it explicitly by placing "marketwatch" in the argument list to
189 Finance::Quote->new().
190
191 This module provides "marketwatch", "nyse", and "nasdaq"
192 fetch methods.
193
194 =head1 LABELS RETURNED
195
196 The following labels are returned:
197
198 =over
199
200 =item name
201
202 =item symbol
203
204 =item last
205
206 =item date
207
208 =item currency
209
210 =back