| 1 |
#!/usr/bin/perl -w |
| 2 |
# This module is based on the Finance::Quote::yahooJSON module |
| 3 |
# |
| 4 |
# This program is free software; you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation; either version 2 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 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 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program; if not, write to the Free Software |
| 16 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
| 17 |
# 02110-1301, USA |
| 18 |
|
| 19 |
# 2025-12-19: sleep_before_query uncommented. Set its parameters |
| 20 |
# to 1 query every 2 seconds. Error message from AV |
| 21 |
# indicates they are limiting free/basic use to one |
| 22 |
# query per second. |
| 23 |
# 2024-04-07: Commented call to sleep_before_query in get_content |
| 24 |
# subroutine. AlphaVantage is not throttling API calls, |
| 25 |
# but limits usage with free API key to 25 per day. |
| 26 |
# 2019-12-01: Added additional labels for net and p_change. Set |
| 27 |
# close to previous close as returned in the JSON. |
| 28 |
# Bruce Schuck (bschuck at asgard hyphen systems dot com) |
| 29 |
|
| 30 |
package Finance::Quote::AlphaVantage; |
| 31 |
|
| 32 |
use strict; |
| 33 |
use JSON qw( decode_json ); |
| 34 |
use HTTP::Request::Common; |
| 35 |
|
| 36 |
our $VERSION = '1.71'; # VERSION |
| 37 |
|
| 38 |
# Alpha Vantage recommends that API call frequency does not extend far |
| 39 |
# beyond ~1 call per second so that they can continue to deliver |
| 40 |
# optimal server-side performance: |
| 41 |
# https://www.alphavantage.co/support/#api-key |
| 42 |
our @alphaqueries=(); |
| 43 |
my $maxQueries = { quantity =>1 , seconds => 2}; # no more than x |
| 44 |
# queries per y |
| 45 |
# seconds, based on |
| 46 |
# https://www.alphavantage.co/support/#support |
| 47 |
|
| 48 |
my $ALPHAVANTAGE_URL = |
| 49 |
'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&datatype=json'; |
| 50 |
|
| 51 |
my %currencies_by_suffix = ( |
| 52 |
|
| 53 |
# Country City/Exchange Name |
| 54 |
'.US' => "USD", # USA AMEX, Nasdaq, NYSE |
| 55 |
'.A' => "USD", # USA American Stock Exchange (ASE) |
| 56 |
'.B' => "USD", # USA Boston Stock Exchange (BOS) |
| 57 |
'.N' => "USD", # USA Nasdaq Stock Exchange (NAS) |
| 58 |
'.O' => "USD", # USA NYSE Stock Exchange (NYS) |
| 59 |
'.OB' => "USD", # USA OTC Bulletin Board |
| 60 |
'.PK' => "USD", # USA Pink Sheets |
| 61 |
'.X' => "USD", # USA US Options |
| 62 |
'.BA' => "ARS", # Argentina Buenos Aires |
| 63 |
'.VI' => "EUR", # Austria Vienna |
| 64 |
'.AX' => "AUD", # Australia |
| 65 |
'.SA' => "BRL", # Brazil Sao Paolo |
| 66 |
'.BR' => "EUR", # Belgium Brussels |
| 67 |
'.TO' => "CAD", # Canada Toronto |
| 68 |
'.TRV' => "CAD", # Canada Toronto Venture |
| 69 |
'.V' => "CAD", # Canada Toronto Venture |
| 70 |
'.TRT' => "CAD", # Canada Toronto |
| 71 |
'.SN' => "CLP", # Chile Santiago |
| 72 |
'.SS' => "CNY", # China Shanghai |
| 73 |
'.SZ' => "CNY", # Shenzhen |
| 74 |
'.CO' => "DKK", # Denmark Copenhagen |
| 75 |
'.PA' => "EUR", # France Paris |
| 76 |
'.BE' => "EUR", # Germany Berlin |
| 77 |
'.BM' => "EUR", # Bremen |
| 78 |
'.D' => "EUR", # Dusseldorf |
| 79 |
'.F' => "EUR", # Frankfurt |
| 80 |
'.FRK' => "EUR", # Frankfurt |
| 81 |
'.H' => "EUR", # Hamburg |
| 82 |
'.HA' => "EUR", # Hanover |
| 83 |
'.MU' => "EUR", # Munich |
| 84 |
'.DEX' => "EUR", # Xetra |
| 85 |
'.ME' => "RUB", # Russia Moscow |
| 86 |
'.SG' => "EUR", # Stuttgart |
| 87 |
'.DE' => "EUR", # XETRA |
| 88 |
'.HK' => "HKD", # Hong Kong |
| 89 |
'.BO' => "INR", # India Bombay |
| 90 |
'.CL' => "INR", # Calcutta |
| 91 |
'.NS' => "INR", # National Stock Exchange |
| 92 |
'.JK' => "IDR", # Indonesia Jakarta |
| 93 |
'.I' => "EUR", # Ireland Dublin |
| 94 |
'.TA' => "ILS", # Israel Tel Aviv |
| 95 |
'.MI' => "EUR", # Italy Milan |
| 96 |
'.KS' => "KRW", # Korea Stock Exchange |
| 97 |
'.KQ' => "KRW", # KOSDAQ |
| 98 |
'.KL' => "MYR", # Malaysia Kuala Lampur |
| 99 |
'.MX' => "MXP", # Mexico |
| 100 |
'.NZ' => "NZD", # New Zealand |
| 101 |
'.AS' => "EUR", # Netherlands Amsterdam |
| 102 |
'.AMS' => "EUR", # Netherlands Amsterdam |
| 103 |
'.OL' => "NOK", # Norway Oslo |
| 104 |
'.LM' => "PEN", # Peru Lima |
| 105 |
'.IN' => "EUR", # Portugal Lisbon |
| 106 |
'.SI' => "SGD", # Singapore |
| 107 |
'.BC' => "EUR", # Spain Barcelona |
| 108 |
'.BI' => "EUR", # Bilbao |
| 109 |
'.MF' => "EUR", # Madrid Fixed Income |
| 110 |
'.MC' => "EUR", # Madrid SE CATS |
| 111 |
'.MA' => "EUR", # Madrid |
| 112 |
'.VA' => "EUR", # Valence |
| 113 |
'.ST' => "SEK", # Sweden Stockholm |
| 114 |
'.STO' => "SEK", # Sweden Stockholm |
| 115 |
'.HE' => "EUR", # Finland Helsinki |
| 116 |
'.S' => "CHF", # Switzerland Zurich |
| 117 |
'.TW' => "TWD", # Taiwan Taiwan Stock Exchange |
| 118 |
'.TWO' => "TWD", # OTC |
| 119 |
'.BK' => "THB", # Thialand Thailand Stock Exchange |
| 120 |
'.TH' => "THB", # ??? From Asia.pm, (in Thai Baht) |
| 121 |
'.L' => "GBP", # United Kingdom London |
| 122 |
'.IL' => "USD", # United Kingdom London USD*100 |
| 123 |
'.VX' => "CHF", # Switzerland |
| 124 |
'.SW' => "CHF", # Switzerland |
| 125 |
); |
| 126 |
|
| 127 |
our $DISPLAY = 'AlphaVantage'; |
| 128 |
our $FEATURES = {'API_KEY' => 'registered user API key'}; |
| 129 |
our @LABELS = qw/date isodate open high low close volume last net p_change/; |
| 130 |
our $METHODHASH = {subroutine => \&alphavantage, |
| 131 |
display => $DISPLAY, |
| 132 |
labels => \@LABELS, |
| 133 |
features => $FEATURES}; |
| 134 |
|
| 135 |
sub labels { |
| 136 |
my %m = methodinfo(); return map {$_ => [@{$m{$_}{labels}}] } keys %m; |
| 137 |
} |
| 138 |
|
| 139 |
sub methodinfo { |
| 140 |
return ( |
| 141 |
alphavantage => $METHODHASH, |
| 142 |
canada => $METHODHASH, |
| 143 |
usa => $METHODHASH, |
| 144 |
nyse => $METHODHASH, |
| 145 |
nasdaq => $METHODHASH, |
| 146 |
); |
| 147 |
} |
| 148 |
|
| 149 |
sub methods { |
| 150 |
my %m = methodinfo(); return map {$_ => $m{$_}{subroutine} } keys %m; |
| 151 |
} |
| 152 |
|
| 153 |
sub sleep_before_query { |
| 154 |
# wait till we can query again |
| 155 |
my $q = $maxQueries->{quantity}-1; |
| 156 |
if ( $#alphaqueries >= $q ) { |
| 157 |
my $time_since_x_queries = time()-$alphaqueries[$q]; |
| 158 |
# print STDERR "LAST QUERY $time_since_x_queries\n"; |
| 159 |
if ($time_since_x_queries < $maxQueries->{seconds}) { |
| 160 |
my $sleeptime = ($maxQueries->{seconds} - $time_since_x_queries) ; |
| 161 |
# print STDERR "SLEEP $sleeptime\n"; |
| 162 |
sleep( $sleeptime ); |
| 163 |
# print STDERR "CONTINUE\n"; |
| 164 |
} |
| 165 |
} |
| 166 |
unshift @alphaqueries, time(); |
| 167 |
pop @alphaqueries while $#alphaqueries>$q; # remove unnecessary data |
| 168 |
# print STDERR join(",",@alphaqueries)."\n"; |
| 169 |
} |
| 170 |
|
| 171 |
sub alphavantage { |
| 172 |
my $quoter = shift; |
| 173 |
|
| 174 |
my @stocks = @_; |
| 175 |
my $quantity = @stocks; |
| 176 |
my ( %info, $reply, $url, $code, $desc, $body, $ticker, $adjust ); |
| 177 |
my $ua = $quoter->user_agent(); |
| 178 |
my $launch_time = time(); |
| 179 |
|
| 180 |
# Since the JSON returned by the GLOBAL_QUOTE API does not specify |
| 181 |
# the currency of the price data, there is no way to determine the |
| 182 |
# correct currency without an additional call to the SYMBOL_SEARCH |
| 183 |
# API. To avoid even slower throttling, this module expects the |
| 184 |
# user to know which securties from certain countries may be traded |
| 185 |
# in the non-ISO4217 currency. |
| 186 |
# Example is LSE traded GBP.L and GBPG.L. GBP.L is traded in GBX, |
| 187 |
# which is also known as GBp, and GBPG.L is traded in the iso-4217 |
| 188 |
# currency GBP (Great Britain Pounds). |
| 189 |
# The user will add ".X" to symbols to return GBX priced securities |
| 190 |
# as GBP. |
| 191 |
|
| 192 |
my $token = exists $quoter->{module_specific_data}->{alphavantage}->{API_KEY} ? |
| 193 |
$quoter->{module_specific_data}->{alphavantage}->{API_KEY} : |
| 194 |
$ENV{"ALPHAVANTAGE_API_KEY"}; |
| 195 |
|
| 196 |
foreach my $stock (@stocks) { |
| 197 |
|
| 198 |
if ($stock =~ /\.X$/) { |
| 199 |
$adjust = 1; |
| 200 |
($ticker = $stock) =~ s/\.X$//; |
| 201 |
} else { |
| 202 |
$adjust = 0; |
| 203 |
$ticker = $stock |
| 204 |
} |
| 205 |
|
| 206 |
if ( !defined $token ) { |
| 207 |
$info{ $stock, 'success' } = 0; |
| 208 |
$info{ $stock, 'errormsg' } = |
| 209 |
'An AlphaVantage API is required. Get an API key at https://www.alphavantage.co'; |
| 210 |
next; |
| 211 |
} |
| 212 |
|
| 213 |
$url = |
| 214 |
$ALPHAVANTAGE_URL |
| 215 |
. '&apikey=' |
| 216 |
. $token |
| 217 |
. '&symbol=' |
| 218 |
. $ticker; |
| 219 |
|
| 220 |
my $get_content = sub { |
| 221 |
sleep_before_query(); |
| 222 |
my $time=int(time()-$launch_time); |
| 223 |
# print STDERR "Query at:".$time."\n"; |
| 224 |
$reply = $ua->request( GET $url); |
| 225 |
|
| 226 |
$code = $reply->code; |
| 227 |
$desc = HTTP::Status::status_message($code); |
| 228 |
$body = $reply->content; |
| 229 |
# print STDERR "AlphaVantage returned: $body\n"; |
| 230 |
}; |
| 231 |
|
| 232 |
&$get_content(); |
| 233 |
|
| 234 |
if ($code != 200) { |
| 235 |
$info{ $stock, 'success' } = 0; |
| 236 |
$info{ $stock, 'errormsg' } = $desc; |
| 237 |
next; |
| 238 |
} |
| 239 |
|
| 240 |
my $json_data; |
| 241 |
eval {$json_data = JSON::decode_json $body}; |
| 242 |
if ($@) { |
| 243 |
$info{ $stock, 'success' } = 0; |
| 244 |
$info{ $stock, 'errormsg' } = $@; |
| 245 |
} |
| 246 |
|
| 247 |
my $try_cnt = 0; |
| 248 |
while (($try_cnt < 5) && ($json_data->{'Note'})) { |
| 249 |
# print STDERR "NOTE:".$json_data->{'Note'}."\n"; |
| 250 |
# print STDERR "ADDITIONAL SLEEPING HERE !"; |
| 251 |
sleep (20); |
| 252 |
&$get_content(); |
| 253 |
eval {$json_data = JSON::decode_json $body}; |
| 254 |
$try_cnt += 1; |
| 255 |
} |
| 256 |
|
| 257 |
if ( !$json_data ) { |
| 258 |
$info{ $stock, 'success' } = 0; |
| 259 |
$info{ $stock, 'errormsg' } = 'Query returned no JSON'; |
| 260 |
next; |
| 261 |
} elsif ( $json_data->{'Error Message'} ) { |
| 262 |
$info{ $stock, 'success' } = 0; |
| 263 |
$info{ $stock, 'errormsg' } = $json_data->{'Error Message'}; |
| 264 |
next; |
| 265 |
} elsif ( $json_data->{'Information'} ) { |
| 266 |
$info{ $stock, 'success' } = 0; |
| 267 |
$info{ $stock, 'errormsg' } = $json_data->{'Information'}; |
| 268 |
next; |
| 269 |
} |
| 270 |
|
| 271 |
my $quote = $json_data->{'Global Quote'}; |
| 272 |
if ( ! $quote ) { |
| 273 |
$info{ $stock, 'success' } = 0; |
| 274 |
$info{ $stock, 'errormsg' } = "json_data does not contain Global Quote"; |
| 275 |
next; |
| 276 |
} |
| 277 |
|
| 278 |
# AlphaVantage can return an empty "Global Quote" when |
| 279 |
# a symbol is not found. |
| 280 |
if ( ! $quote->{'01. symbol'} ) { |
| 281 |
$info{ $stock, 'success' } = 0; |
| 282 |
$info{ $stock, 'errormsg' } = "Symbol $stock not found."; |
| 283 |
next; |
| 284 |
} |
| 285 |
|
| 286 |
# %ts holds data as |
| 287 |
# { |
| 288 |
# "Global Quote": { |
| 289 |
# "01. symbol": "SOLB.BR", |
| 290 |
# "02. open": "104.2000", |
| 291 |
# "03. high": "104.9500", |
| 292 |
# "04. low": "103.4000", |
| 293 |
# "05. price": "104.0000", |
| 294 |
# "06. volume": "203059", |
| 295 |
# "07. latest trading day": "2019-11-29", |
| 296 |
# "08. previous close": "105.1500", |
| 297 |
# "09. change": "-1.1500", |
| 298 |
# "10. change percent": "-1.0937%" |
| 299 |
# } |
| 300 |
# } |
| 301 |
|
| 302 |
# remove trailing percent sign, if present |
| 303 |
$quote->{'10. change percent'} =~ s/\%$//; |
| 304 |
|
| 305 |
$info{ $stock, 'success' } = 1; |
| 306 |
$info{ $stock, 'success' } = 1; |
| 307 |
$info{ $stock, 'symbol' } = $quote->{'01. symbol'}; |
| 308 |
$info{ $stock, 'open' } = $quote->{'02. open'}; |
| 309 |
$info{ $stock, 'high' } = $quote->{'03. high'}; |
| 310 |
$info{ $stock, 'low' } = $quote->{'04. low'}; |
| 311 |
$info{ $stock, 'last' } = $quote->{'05. price'}; |
| 312 |
$info{ $stock, 'volume' } = $quote->{'06. volume'}; |
| 313 |
$info{ $stock, 'close' } = $quote->{'08. previous close'}; |
| 314 |
$info{ $stock, 'net' } = $quote->{'09. change'}; |
| 315 |
$info{ $stock, 'p_change' } = $quote->{'10. change percent'}; |
| 316 |
$info{ $stock, 'method' } = 'alphavantage'; |
| 317 |
$quoter->store_date( \%info, $stock, { isodate => $quote->{'07. latest trading day'} } ); |
| 318 |
|
| 319 |
# deduce currency |
| 320 |
if ( $ticker =~ /(\..*)/ ) { |
| 321 |
my $suffix = uc $1; |
| 322 |
if ( $currencies_by_suffix{$suffix} ) { |
| 323 |
$info{ $stock, 'currency' } = $currencies_by_suffix{$suffix}; |
| 324 |
|
| 325 |
# divide .X quotes by 100 |
| 326 |
if ( $adjust == 1 ) { |
| 327 |
foreach my $field ( $quoter->default_currency_fields ) { |
| 328 |
next unless ( $info{ $stock, $field } ); |
| 329 |
$info{ $stock, $field } = |
| 330 |
$quoter->scale_field( $info{ $stock, $field }, |
| 331 |
0.01 ); |
| 332 |
} |
| 333 |
} |
| 334 |
# divide USD quotes by 100 if suffix is '.IL' |
| 335 |
if ( ($suffix eq '.IL') && ($info{$stock,'currency'} eq 'USD') ) { |
| 336 |
foreach my $field ( $quoter->default_currency_fields ) { |
| 337 |
next unless ( $info{ $stock, $field } ); |
| 338 |
$info{ $stock, $field } = |
| 339 |
$quoter->scale_field( $info{ $stock, $field }, |
| 340 |
0.01 ); |
| 341 |
} |
| 342 |
} |
| 343 |
} |
| 344 |
} |
| 345 |
else { |
| 346 |
$info{ $stock, 'currency' } = 'USD'; |
| 347 |
} |
| 348 |
|
| 349 |
$info{ $stock, "currency_set_by_fq" } = 1; |
| 350 |
|
| 351 |
} |
| 352 |
|
| 353 |
return wantarray() ? %info : \%info; |
| 354 |
} |
| 355 |
1; |
| 356 |
|
| 357 |
=head1 NAME |
| 358 |
|
| 359 |
Finance::Quote::AlphaVantage - Obtain quotes from https://alphavantage.co |
| 360 |
|
| 361 |
=head1 SYNOPSIS |
| 362 |
|
| 363 |
use Finance::Quote; |
| 364 |
|
| 365 |
$q = Finance::Quote->new('AlphaVantage', alphavantage => {API_KEY => 'your-alphavantage-api-key'}); |
| 366 |
|
| 367 |
%info = $q->fetch('alphavantage', 'IBM', 'AAPL'); |
| 368 |
|
| 369 |
=head1 DESCRIPTION |
| 370 |
|
| 371 |
This module fetches information from https://www.alphavantage.co. |
| 372 |
|
| 373 |
This module is loaded by default on a Finance::Quote object. It's also possible |
| 374 |
to load it explicitly by placing "AlphaVantage" in the argument list to |
| 375 |
Finance::Quote->new(). |
| 376 |
|
| 377 |
This module provides the "alphavantage" fetch method. |
| 378 |
|
| 379 |
=head1 API_KEY |
| 380 |
|
| 381 |
https://www.alphavantage.co requires users to register and obtain an API key, which |
| 382 |
is also called a token. The token is a sequence of random characters. |
| 383 |
|
| 384 |
The API key may be set by either providing a module specific hash to |
| 385 |
Finance::Quote->new as in the above example, or by setting the environment |
| 386 |
variable ALPHAVANTAGE_API_KEY. |
| 387 |
|
| 388 |
=head1 LABELS RETURNED |
| 389 |
|
| 390 |
The following labels may be returned by Finance::Quote::AlphaVantage : |
| 391 |
symbol, open, close, high, low, last, volume, method, isodate, currency. |
| 392 |
|
| 393 |
=head1 CAVEATs |
| 394 |
|
| 395 |
Since the JSON returned by the GLOBAL_QUOTE API does not specify |
| 396 |
the currency of the price data, there is no way to determine the |
| 397 |
correct currency without an additional call to the SYMBOL_SEARCH |
| 398 |
API. To avoid even slower throttling, this module expects the |
| 399 |
user to know which securties from certain countries may be traded |
| 400 |
in the non-ISO4217 currency. |
| 401 |
|
| 402 |
An example are London Stock Exchange traded GBP.L (Global Petroleum Limited) |
| 403 |
and GBPG.L |
| 404 |
(Goldman Sachs Access UK Gilts 1-10 Years UCITS ETF CLASS GBP (Dist)). |
| 405 |
GBP.L is traded in GBX, which is also known as GBp (Great Britain Pence), |
| 406 |
and GBPG.L is traded in the iso-4217 currency GBP (Great Britain Pounds). |
| 407 |
The user will need to add ".X" to symbols to return GBX priced securities |
| 408 |
as GBP. For the example above the user would use the symbol GBP.L.X in |
| 409 |
the call to the alphavantage method for the prices to be output as GBP. |
| 410 |
|
| 411 |
=cut |