Debian Codegraph @

lib/Finance/Quote/Consorsbank.pm

raw
1 #!/usr/bin/perl -w
2
3 # Copyright (C) 2023, Stephan Gambke <[email protected]>
4
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 # 02110-1301, USA
17
18 require 5.005;
19
20 use strict;
21 use warnings;
22
23 package Finance::Quote::Consorsbank;
24
25 use LWP::UserAgent;
26 use JSON qw( decode_json );
27 use Date::Parse qw(str2time);
28 use POSIX qw(strftime);
29 use Encode qw(encode_utf8);
30
31 use constant DEBUG => $ENV{DEBUG};
32 use if DEBUG, 'Smart::Comments';
33 use if DEBUG, 'Data::Dumper';
34
35 our $VERSION = '1.71'; # VERSION
36
37 my $CONSORS_URL = 'https://www.consorsbank.de/web-financialinfo-service/api/marketdata/stocks?';
38 my $CONSORS_SOURCE_BASE_URL = 'https://www.consorsbank.de/web/Wertpapier/';
39
40 our $DISPLAY = 'Consorsbank - Consorsbank API';
41 our $FEATURES = { 'EXCHANGE' => 'select market place (i.e. "gettex", "Xetra", "Tradegate")' };
42
43 # Correspondence of FQ labels to Consorsbank API fields
44
45 # success Did the stock successfully return information? (true/false)
46 # errormsg Info.Errors.ERROR_MESSAGE If success is false, this field may contain the reason why.
47 # symbol Info.ID.SYMBOL ticker symbol
48 # wkn Info.ID.WKN WKN
49 # symbol Info.ID.ISIN ISIN
50 # name BasicV1.NAME_SECURITY Company or Mutual Fund Name
51 # method 'consorsbank' The module (as could be passed to fetch) which found this information.
52 # source Source URL, either general website or direct human-readable deep link
53 # exchange CONSORS_EXCHANGE_NAME The exchange the information was obtained from.
54 # currency ISO_CURRENCY ISO currency code
55
56 # ask ASK Ask
57 # avg_vol Average Daily Vol
58 # bid BID Bid
59 # cap Market Capitalization
60 # close PREVIOUS_LAST Previous Close
61 # date DATETIME_PRICE Last Trade Date (MM/DD/YY format)
62 # day_range HIGH, LOW Day's Range
63 # div Dividend per Share
64 # div_date Dividend Pay Date
65 # div_yield Dividend Yield
66 # eps Earnings per Share
67 # ex_div Ex-Dividend Date.
68 # high HIGH Highest trade today
69 # last PRICE Last Price
70 # low LOW Lowest trade today
71 # nav Net Asset Value
72 # net PERFORMANCE Net Change
73 # open FIRST Today's Open
74 # p_change PERFORMANCE_PCT Percent Change from previous day's close
75 # pe P/E Ratio
76 # time DATETIME_PRICE Last Trade Time
77 # type The type of equity returned
78 # volume TOTAL_VOLUME Volume
79 # year_range HIGH_PRICE_1_YEAR - LOW_PRICE_1_YEAR 52-Week Range
80 # yield Yield (usually 30 day avg)
81
82 our @LABELS = qw/
83 symbol wkn isin
84 name
85 method
86 source
87 exchange
88 exchanges
89 currency
90 ask
91 bid
92 date
93 day_range
94 high
95 last
96 low
97 net
98 open
99 close
100 p_change
101 volume
102 year_range
103 /;
104
105 our $METHODHASH = {subroutine => \&consorsbank,
106 display => $DISPLAY,
107 labels => \@LABELS,
108 features => $FEATURES};
109
110 sub methodinfo {
111 return (
112 consorsbank => $METHODHASH,
113 europe => $METHODHASH,
114 );
115 }
116
117 sub labels {
118 my %m = methodinfo(); return map {$_ => [@{$m{$_}{labels}}] } keys %m;
119 }
120
121 sub methods {
122 my %m = methodinfo(); return map {$_ => $m{$_}{subroutine} } keys %m;
123 }
124
125 sub consorsbank {
126
127 # a Finance::Quote object
128 my Finance::Quote $quoter = shift;
129
130 # a list of zero or more symbol names
131 my @symbols = @_ or return;
132
133 # user_agent() provides a ready-to-use LWP::UserAgent
134 my $ua = $quoter->user_agent;
135
136 my %info;
137
138 my %mapping = (# in QuotesV1, PriceV2, ExchangesV2
139 'exchange' => 'CONSORS_EXCHANGE_NAME',
140 'currency' => 'ISO_CURRENCY', # also 'UNIT_PRICE' exists
141 'p_change' => 'PERFORMANCE_PCT');
142
143 my %map_price_v2 = (# QuotesV1 & PriceV2 keys
144 'ask' => 'ASK',
145 'bid' => 'BID',
146 'close' => 'PREVIOUS_LAST',
147 'open' => 'FIRST',
148 'high' => 'HIGH',
149 'last' => 'PRICE',
150 'low' => 'LOW',
151 'net' => 'PERFORMANCE',
152 'volume' => 'TOTAL_VOLUME');
153
154 my %map_quotes_v1 = ( %map_price_v2,
155 # QuotesV1 keys
156 'year_low' => 'LOW_PRICE_1_YEAR',
157 'year_high' => 'HIGH_PRICE_1_YEAR');
158
159 my %map_exchanges_v2 = (# ExchangesV2 keys
160 'last' => 'PRICE',
161 'ask' => 'PRICE_ASK',
162 'bid' => 'PRICE_BID');
163
164 my $labels = $quoter->get_required_labels;
165 $labels = \@LABELS unless(scalar(@$labels));
166
167 my $require_quotes_v1 = grep { exists($map_quotes_v1{$_})
168 and not exists($map_exchanges_v2{$_})
169 } @$labels;
170
171 my $require_exchanges = grep { $_ eq 'exchanges' } @$labels;
172
173 my $exchange = exists $quoter->{module_specific_data}->{consorsbank}->{EXCHANGE} ?
174 $quoter->{module_specific_data}->{consorsbank}->{EXCHANGE} : undef;
175
176 if ($exchange and not $require_quotes_v1) {
177 %mapping = (%mapping, %map_exchanges_v2);
178 } else {
179 %mapping = (%mapping, %map_quotes_v1);
180 }
181
182 my %map_basic_v1_id = (# BasicV1.ID keys
183 'symbol' => 'SYMBOL',
184 'wkn' => 'WKN',
185 'isin' => 'ISIN',
186 'notation_id' => 'ID_NOTATION');
187
188 for my $symbol (@symbols) {
189
190 ### $symbol
191
192 $info{ $symbol, 'symbol' } = $symbol;
193 $info{ $symbol, 'success' } = 0;
194 $info{ $symbol, 'errormsg' } = '';
195
196 my $get_json = sub {
197 my $query = shift;
198 my $response = $ua->get($query);
199
200 unless ($response->is_success) {
201 $info{ $symbol, 'errormsg' } = "Unable to fetch data from the Consorsbank server for $symbol. Error: " . $response->status_line;
202 return;
203 }
204
205 unless ($response->header('content-type') =~ m|application/json|i) {
206 $info{ $symbol, 'errormsg' } = "Invalid content-type from Consorsbank server for $symbol. Expected: application/json, received: " . $response->header('content-type');
207 return;
208 }
209
210 my $json = encode_utf8($response->content);
211
212 ### [<here>] $json:
213 ### $json
214
215 my $data;
216 eval { $data = JSON::decode_json($json) };
217
218 if ($@) {
219 $info{ $symbol, 'errormsg' } = "Failed to parse JSON data for $symbol. Error: $@.";
220 ### $@
221 return;
222 }
223
224 ### [<here>] $data:
225 ### $data
226
227 if ( defined $data->[0]{'Info'}{'Errors'} ){
228 ### API Error: $data->[0]{'Info'}{'Errors'}
229
230 if ( $data->[0]{'Info'}{'Errors'}[0]{'ERROR_CODE'} eq 'IDMS' ){
231 $info{ $symbol, 'errormsg' } = "Invalid symbol: $symbol";
232 } else {
233 $info{ $symbol, 'errormsg' } = $data->[0]{'Info'}{'Errors'}[0]{'ERROR_MESSAGE'}
234 }
235 return;
236 }
237
238 return $data;
239 };
240
241 my ($data, $quote);
242 if ($exchange) {
243 $data = &$get_json($CONSORS_URL . "id=$symbol&field=ExchangesV2&field=BasicV1") or next;
244 $info{ $symbol, 'exchanges' } = [ map { $_->{'CONSORS_EXCHANGE_NAME'} } @{$data->[0]{'ExchangesV2'}} ];
245
246 ($quote) = grep { $_->{'CONSORS_EXCHANGE_NAME'} eq $exchange
247 or $_->{'CONSORS_EXCHANGE_CODE'} eq '_' .$exchange
248 } @{$data->[0]{'ExchangesV2'}};
249 unless($quote) {
250 $info{ $symbol, 'errormsg' } = "Marketplace not found: $exchange";
251 next;
252 }
253 if ($require_quotes_v1) {
254 my ($id, $code) = ($quote->{'CONSORS_ID'}, $quote->{'CONSORS_EXCHANGE_CODE'});
255 $data = &$get_json($CONSORS_URL . "id=$id&field=QuotesV1&field=BasicV1&rtExchangeCode=$code") or next;
256 $quote = $data->[0]{'QuotesV1'}[0];
257 }
258 } else {
259 if ($require_exchanges) {
260 $data = &$get_json($CONSORS_URL . "id=$symbol&field=QuotesV1&field=BasicV1&field=ExchangesV2") or next;
261 $info{ $symbol, 'exchanges' } = [ map { $_->{'CONSORS_EXCHANGE_NAME'} } @{$data->[0]{'ExchangesV2'}} ];
262 } else {
263 $data = &$get_json($CONSORS_URL . "id=$symbol&field=QuotesV1&field=BasicV1") or next;
264 }
265 $quote = $data->[0]{'QuotesV1'}[0];
266
267 #$quote = $data->[0]{'PriceV2'};
268 }
269
270 ### [<here>] $symbol:
271 ### $symbol
272
273 while ((my $fqkey, my $cbkey) = each (%map_basic_v1_id)) {
274 $info{ $symbol, $fqkey } = $data->[0]{'BasicV1'}{'ID'}{$cbkey} if (defined $data->[0]{'BasicV1'}{'ID'}{$cbkey});
275 }
276
277 $info{ $symbol, 'name' } = $data->[0]{'BasicV1'}{'NAME_SECURITY'} if (defined $data->[0]{'BasicV1'}{'NAME_SECURITY'});
278 $info{ $symbol, 'method' } = 'consorsbank';
279 $info{ $symbol, 'source' } = $CONSORS_SOURCE_BASE_URL . $data->[0]{'Info'}{'ID'};
280
281 while ((my $fqkey, my $cbkey) = each (%mapping)) {
282 $info{ $symbol, $fqkey } = $quote->{$cbkey} if (exists $quote->{ $cbkey } and defined $quote->{ $cbkey } );
283 }
284
285 # in QuotesV1, PriceV2, ExchangesV2
286 if (defined($quote->{'DATETIME_PRICE'})) {
287 my $utc_timestamp = str2time($quote->{'DATETIME_PRICE'});
288 $info{ $symbol, 'time' } = strftime("%H:%M", localtime($utc_timestamp)); # local time zone
289 $quoter->store_date(\%info, $symbol, {isodate => strftime("%Y-%m-%d", localtime($utc_timestamp))});
290 }
291
292 $info{ $symbol, 'day_range' } = $info{ $symbol, 'low' } . ' - ' . $info{ $symbol, 'high' }
293 if (exists $info{ $symbol, 'low' } && exists $info{ $symbol, 'high' });
294
295 $info{ $symbol, 'year_range' } = $info{ $symbol, 'year_low' } . ' - ' . $info{ $symbol, 'year_high' }
296 if (exists $info{ $symbol, 'year_low' } && exists $info{ $symbol, 'year_high' });
297
298 unless (defined $info{ $symbol, 'last'} ) {
299 $info{ $symbol, 'errormsg' } = "The server did not return a price for $symbol.";
300 next;
301 }
302
303 $info{ $symbol, 'success' } = 1;
304 }
305
306 ### [<here>] %info:
307 ### %info
308
309 return wantarray() ? %info : \%info;
310 }
311 1;
312 __END__
313
314 =head1 NAME
315
316 Finance::Quote::Consorsbank - Obtain quotes from Consorsbank.
317
318 =head1 SYNOPSIS
319
320 use Finance::Quote;
321
322 $q = Finance::Quote->new;
323 or
324 $q = Finance::Quote->new("Consorsbank", "consorsbank" => { "EXCHANGE" => "Xetra" });
325
326 %stockinfo = $q->fetch("consorsbank","DE0007664005"); # Only query consorsbank using ISIN.
327 %stockinfo = $q->fetch("consorsbank","766400"); # Only query consorsbank using WKN.
328 %stockinfo = $q->fetch("europe","DE0007664005"); # Failover to other sources OK.
329
330 @exchanges = @{ $info{ "DE0007664005", "exchanges" } }; # List of available marketplaces
331
332 =head1 DESCRIPTION
333
334 This module obtains information from Consorsbank (https://www.consorsbank.de).
335
336 It accepts ISIN or German WKN as requested symbol.
337
338 This module is loaded by default on a Finance::Quote object. It's
339 also possible to load it explicitly by placing "Consorsbank" in the argument
340 list to Finance::Quote->new().
341
342 This module provides both the "consorsbank" and "europe" fetch methods.
343 Please use the "europe" fetch method if you wish to have failover with other
344 sources for European stock exchanges. Using the "consorsbank" method will
345 guarantee that your information only comes from the Consorsbank service.
346
347 =head1 EXCHANGE
348
349 https://www.consorsbank.de/ supports different market places. A default is not specified.
350
351 "Xetra" alias "GER"
352 "Tradegate" alias "GAT"
353 "gettex" alias "TRO"
354 "Berlin" alias "BER"
355 ... any many more ...
356
357 The EXCHANGE may be set by providing a module specific hash to
358 Finance::Quote->new as in the above example (optional).
359
360 =head1 LABELS RETURNED
361
362 The following labels may be returned by Finance::Quote::Consorsbank:
363
364 symbol, wkn, isin, name, method, source, exchange, exchanges, currency,
365 ask, bid, date, day_range, high, last, low, net, open, close,
366 p_change, volume, year_range
367
368 =cut