Debian Codegraph @

lib/Finance/Quote/Stooq.pm

raw
1 #!/usr/bin/perl -w
2 # vi: set ts=2 sw=2 noai expandtab 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::Stooq;
23
24 use strict;
25 use warnings;
26
27 use Encode qw(decode encode);
28 use LWP::UserAgent;
29 use HTTP::Request::Common;
30 use HTTP::CookieJar::LWP ();
31 use HTTP::Cookies;
32 use HTML::TableExtract;
33
34 use constant DEBUG => $ENV{DEBUG};
35 use if DEBUG, 'Smart::Comments', '###';
36
37 our $VERSION = '1.71'; # VERSION
38
39 our $DISPLAY = 'Stooq - Warsaw Stock Exchange';
40 our @LABELS = qw/symbol name open high low last bid ask date currency method/;
41 our $METHODHASH = {subroutine => \&stooq,
42 display => $DISPLAY,
43 labels => \@LABELS};
44
45 sub methodinfo {
46 return (
47 stooq => $METHODHASH,
48 europe => $METHODHASH,
49 poland => $METHODHASH,
50 );
51 }
52
53 sub labels { my %m = methodinfo(); return map {$_ => [@{$m{$_}{labels}}] } keys %m; }
54
55 sub methods {
56 my %m = methodinfo(); return map {$_ => $m{$_}{subroutine} } keys %m;
57 }
58
59 my $STOOQ_URL = 'https://stooq.com/q/?s=';
60
61 my %currencies_by_link = (
62 '?i=21' => "EUR", # Europe (€)
63 '?i=23' => "GBP", # United Kingdom (£)
64 '?i=25' => "HKD", # Hong Kong (HK$)
65 '?i=30' => "HUF", # Hungary (Ft)
66 '?i=39' => "JPY", # Japan (¥)
67 '?i=60' => "PLN", # Poland (zł)
68 '?i=77' => "USD", # United States ($)
69 );
70
71 my %currencies_by_symbol = (
72 '&pound;' => "GBP", # United Kingdom (£)
73 'p.' => "GBX", # United Kingdom (penny)
74 '&euro;' => "EUR", # Europe (€)
75 "z\x{142}" => "PLN", # Poland (zł)
76 '$' => "USD", # United States ($)
77 '&cent;' => "USX", # United States (¢)
78 'HK$' => "HKD", # Hong Kong (HK$)
79 '&yen;' => "JPY", # Japan (¥)
80 'Ft' => "HUF", # Hungary (Ft)
81 );
82
83 ### [<now>] Currencies by Symbol: %currencies_by_symbol
84
85 sub stooq {
86
87 my $quoter = shift;
88 my @stocks = @_;
89 my (%info, $tree, $table, $pricetable, $url, $reply);
90
91 my $cj = HTTP::Cookies->new();
92 # Cookies content gleaned from browser session
93 $cj->set_cookie(0, 'cookie_user', '%3F+++1dllg000G+1100d1300c3%7Clrq', '/', '.stooq.com');
94 $cj->set_cookie(0, 'cookie_uu', '260114000', '/', '.stooq.com');
95 $cj->set_cookie(0, 'FCCDCF', '%5Bnull%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%5B%5B32%2C%22%5B%5C%22ab16ab99-60a0-4da1-a296-29c8a27efbf9%5C%22%2C%5B1767931790%2C786000000%5D%5D%22%5D%2C%5B13%2C%22%5B%5C%22DBABL~BVQqAAAAAg%5C%22%2C%5B%5B7%2C%5B1768425873%2C984063000%5D%5D%5D%5D%22%5D%5D%5D', '/', '.stooq.com');
96 $cj->set_cookie(0, 'FCNEC', '%5B%5B%22AKsRol_Zywhkz7ukryuiQZ7evZsxa0eSbPMEpqvZUwq6Kmf32IqN4xQFgJjIG_fDDxo4f5sLKIXXGsrdQayx3tROTwoyC8BZX4rNDu3fBfzCikX_gkuhCra5dJotNToqdQrxouYXlgE_k7KTmpnQn7AEOImeVQrz2g%3D%3D%22%5D%5D', '/', '.stooq.com');
97 $cj->set_cookie(0, 'PHPSESSID', '3vqtfg7shbf23iog9frtbqdn15', '/', 'stooq.com');
98 $cj->set_cookie(0, 'privacy', '1768598448', '/', 'stooq.com');
99 $cj->set_cookie(0, 'uid', 'usb132zim841xr4doi8j12uk4a', '/', 'stooq.com');
100
101 my $ua = $quoter->user_agent();
102
103 $ua->cookie_jar($cj);
104
105 $ua->default_header('Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7');
106 $ua->default_header('Accept-Encoding' => 'gzip, deflate, br, zstd');
107 $ua->default_header('Accept-Language' => 'en-US,en;q=0.9');
108 $ua->default_header('Host' => 'stooq.com');
109 $ua->default_header('Pragma' => 'no-cache');
110 $ua->default_header('Upgrade-Insecure-Requests' => '1');
111 $ua->default_header('User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36');
112
113 foreach my $stock (@stocks) {
114
115 $url = $STOOQ_URL . $stock;
116 $reply = $ua->request( GET $url );
117
118 my $code = $reply->code;
119 my $desc = HTTP::Status::status_message($code);
120 my $headers = $reply->headers_as_string;
121 my $body = $reply->decoded_content;
122
123 ### Headers: $headers
124 ### Body: $body
125
126 my ($name, $bid, $ask, $last, $open, $high, $low, $date, $currency);
127 my ($te, $table);
128
129 $info{ $stock, "symbol" } = $stock;
130
131 if ( $code == 200 ) {
132
133 # Use HTML::TableExtract to parse HTML in $body
134
135 # The table with the security name is the only table
136 # with bgcolor=e9e9e9 style=z-index:1
137 $te = HTML::TableExtract->new(
138 attribs => { bgcolor => 'e9e9e9', style => 'z-index:1' } );
139 if (($te->parse($body)) && ($table = $te->first_table_found)) {
140 ### NameTable Rows: $table->rows()
141 ($name) = $table->cell(0,1) =~ m|^.*?(\w.*)$|;
142 $te->eof;
143 }
144
145 # The table with the price data is the only table with
146 # attribute id='t1'
147 $te = HTML::TableExtract->new( keep_html => 1,
148 attribs => { id => 't1' } );
149 if (($te->parse($body)) && ($table = $te->first_table_found)) {
150 (my $last) = $table->cell(0,0) =~ m|^.+>([\d\.]+)<|;
151
152 # usually currency is embedded in an A tag
153 # curency default: td > b[> span_with_price] + "&nbsp;" + _a_linking_to_currency
154 # curency USD/HUF: td > b > _a_linking_to_currency + "&nbsp;" + span_with_price
155 # except for commodities there's no A tag:
156 # commodities: td > b[> span_with_price] + "&nbsp;_currency_without_link_"
157 ### [<now>] Cell 0,0: $table->cell(0,0)
158 (my $currlink) = $table->cell(0,0) =~ m|<a href=t/(\?i=\d+)>|;
159 if ( ($currlink) && ($currencies_by_link{$currlink}) ) {
160 $currency = $currencies_by_link{$currlink};
161 } else {
162 (my $currsymbol) = $table->cell(0,0)
163 =~ m#[\d\.]+</span></b>&nbsp;(.+)/(ozt|lb|t|gal|bbl|bu|mmBtu)#;
164 ### [<now>] CurrSymbol: $currsymbol
165 if ( ($currsymbol) && ($currencies_by_symbol{$currsymbol}) ) {
166 $currency = $currencies_by_symbol{$currsymbol};
167 }
168 }
169
170 ### [<now>] Currency: $currency
171
172 (my $date) = $table->cell(0,1) =~ m|Date.+>(\d{4}-\d{2}-\d{2})<|;
173 (my $high, my $low) = $table->cell(1,1)
174 =~ m|.+>([\d\.]+)<.+>([\d\.]+)<|;
175 (my $open) = $table->cell(3,0) =~ m|Open.+>([\d\.]+)<|;
176 (my $bid) = $table->cell(4,0) =~ m|Bid.+>([\d\.]+)<|;
177 (my $ask) = $table->cell(4,1) =~ m|Ask.+>([\d\.]+)<|;
178 # If last and date are defined, save values in hash
179 if ( ($last) && ($date) && ($currency) ) {
180 $info{ $stock, 'success' } = 1;
181 $info{ $stock, 'method' } = 'stooq';
182 $info{ $stock, 'name' } = $name;
183 $info{ $stock, 'last' } = $last;
184 $info{ $stock, 'currency' } = $currency;
185 $info{ $stock, 'open' } = $open;
186 $info{ $stock, 'high' } = $high;
187 $info{ $stock, 'low' } = $low;
188 $info{ $stock, 'bid' } = $bid if ($bid);
189 $info{ $stock, 'ask' } = $ask if ($ask);
190 $quoter->store_date(\%info, $stock, { isodate => $date });
191 # Adjust/scale price data if currency is GBX (GBp) or USX (USc)
192 if ( ( $currency eq 'GBX' ) || ( $currency eq 'USX' ) ) {
193 foreach my $field ( $quoter->default_currency_fields ) {
194 next unless ( $info{ $stock, $field } );
195 $info{ $stock, $field } =
196 $quoter->scale_field( $info{ $stock, $field }, 0.01 );
197 }
198 if ( $info{ $stock, 'currency' } eq 'GBX' ) {
199 $info{ $stock, 'currency' } = 'GBP';
200 } else {
201 $info{ $stock, 'currency' } = 'USD';
202 }
203 }
204 } else {
205 $info{ $stock, "success" } = 0;
206 $info{ $stock, "errormsg" } =
207 "Error retrieving quote for $stock. Could not parse HTML returned from $url.";
208 }
209 } else {
210 $te->eof;
211 $info{ $stock, "success" } = 0;
212 $info{ $stock, "errormsg" } =
213 "Error retrieving quote for $stock. Could not parse HTML returned from $url.";
214 }
215
216 } else { # HTTP Request failed (code != 200)
217 $info{ $stock, "success" } = 0;
218 $info{ $stock, "errormsg" } =
219 "Error retrieving quote for $stock. Attempt to fetch the URL $url resulted in HTTP response $code ($desc)";
220 }
221
222 }
223
224 return wantarray() ? %info : \%info;
225 return \%info;
226
227 }
228
229 1;
230
231 __END__
232
233 =head1 NAME
234
235 Finance::Quote::stooq - Obtain quotes from stooq Stock Exchange.
236
237 =head1 SYNOPSIS
238
239 use Finance::Quote;
240
241 $q = Finance::Quote->new;
242
243 %info = $q->fetch("stooq", "ISLN.UK"); # Only query stooq
244
245 %info = $q->fetch("poland", "LRQ"); # Failover to other sources OK.
246
247 =head1 DESCRIPTION
248
249 This module fetches information from L<https://stooq.com/>.
250
251 This module is loaded by default on a Finance::Quote object. It's also possible
252 to load it explicitly by placing "stooq" in the argument list to
253 Finance::Quote->new().
254
255 This module provides "stooq", "poland", and "europe" fetch methods.
256
257 Information obtained by this module may be covered by Warsaw Stock
258 Exchange terms and conditions.
259
260 =head1 LABELS RETURNED
261
262 The following labels are returned:
263
264 =over
265
266 =item name
267
268 =item symbol
269
270 =item open
271
272 =item high
273
274 =item low
275
276 =item last
277
278 =item bid
279
280 =item ask
281
282 =item date
283
284 =item currency
285
286 =back
287
288 =head1 Caveat
289
290 When accessed from Europe the website requires cookie consent. Many of the
291 cookies are set via Google's "Google's Privacy & messaging tool
292 (formerly known as Google Funding Choices)". It may be necessary to
293 manually capture cookies in a browser and replace the values in this
294 module.
295