Debian Codegraph @

lib/Finance/Quote/Finnhub.pm

raw
1 #!/usr/bin/perl -w
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
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 package Finance::Quote::Finnhub;
19
20 use strict;
21 use warnings;
22
23 use JSON qw( decode_json );
24 use HTTP::Request::Common;
25
26 use constant DEBUG => $ENV{DEBUG};
27 use if DEBUG, 'Smart::Comments', '###';
28
29 our $VERSION = '1.71'; # VERSION
30
31 my $FINNHUB_URL = 'https://finnhub.io/api/v1/';
32
33 # Finnhub's free tier permits 60 API calls per minute, and this module
34 # makes one call per requested symbol, so a batch of more than 60 symbols
35 # would exceed the limit if fired off back to back. @finnhub_calls holds
36 # the timestamps of recent API calls; _throttle uses it as a sliding
37 # window to pace requests once the limit is neared.
38 my $MAX_PER_MIN = 60;
39 our @finnhub_calls = ();
40
41 our $DISPLAY = 'Finnhub - finnhub.io';
42 our $FEATURES = {'API_KEY' => 'registered user API key'};
43 our @LABELS = qw/symbol last open high low close net p_change date isodate currency method/;
44 our $METHODHASH = {subroutine => \&finnhub,
45 display => $DISPLAY,
46 labels => \@LABELS,
47 features => $FEATURES};
48
49 sub methodinfo {
50 return (
51 finnhub => $METHODHASH,
52 usa => $METHODHASH,
53 nyse => $METHODHASH,
54 nasdaq => $METHODHASH,
55 );
56 }
57
58 sub labels {
59 my %m = methodinfo();
60 return map {$_ => [@{$m{$_}{labels}}] } keys %m;
61 }
62
63 sub methods {
64 my %m = methodinfo();
65 return map {$_ => $m{$_}{subroutine} } keys %m;
66 }
67
68 # Pace API calls to stay within the allowed calls-per-minute. This is a
69 # sliding window: the most recent $max timestamps are kept, and a call is
70 # only delayed once $max calls have already been made in the last 60
71 # seconds. Small batches therefore run at full speed.
72 sub _throttle {
73 my $max = shift;
74 my $q = $max - 1;
75 if ( $#finnhub_calls >= $q ) {
76 my $elapsed = time() - $finnhub_calls[$q];
77 sleep( 60 - $elapsed ) if $elapsed < 60;
78 }
79 unshift @finnhub_calls, time();
80 pop @finnhub_calls while $#finnhub_calls > $q;
81 return;
82 }
83
84 # Make a throttled GET request. If Finnhub still returns 429 (rate
85 # limited) -- e.g. because the key is shared with another application --
86 # wait for the period it advertises and retry a bounded number of times.
87 sub _request {
88 my ( $ua, $url, $max ) = @_;
89 my $reply;
90 for ( 1 .. 3 ) {
91 _throttle($max);
92 $reply = $ua->request( GET $url );
93 last unless $reply->code == 429;
94
95 my $wait = $reply->header('Retry-After');
96 if ( !defined $wait ) {
97 my $reset = $reply->header('X-Ratelimit-Reset');
98 $wait = defined $reset ? $reset - time() : 60;
99 }
100 $wait = 1 if $wait < 1;
101 $wait = 60 if $wait > 60;
102 sleep $wait;
103 }
104 return $reply;
105 }
106
107 sub finnhub {
108
109 my $quoter = shift;
110 my @stocks = @_;
111 my (%info, $url, $reply);
112 my $ua = $quoter->user_agent();
113
114 # The API key (token) may be supplied either through a module specific
115 # hash passed to Finance::Quote->new, or via the FINNHUB_API_KEY
116 # environment variable.
117 my $token = exists $quoter->{module_specific_data}->{finnhub}->{API_KEY}
118 ? $quoter->{module_specific_data}->{finnhub}->{API_KEY}
119 : $ENV{'FINNHUB_API_KEY'};
120
121 # Calls allowed per minute. Defaults to the free tier (60); a paid key
122 # can raise it through the module specific data.
123 my $max = exists $quoter->{module_specific_data}->{finnhub}->{CALLS_PER_MINUTE}
124 ? $quoter->{module_specific_data}->{finnhub}->{CALLS_PER_MINUTE}
125 : $MAX_PER_MIN;
126
127 foreach my $stock (@stocks) {
128
129 $info{ $stock, 'symbol' } = $stock;
130
131 if ( !defined $token ) {
132 $info{ $stock, 'success' } = 0;
133 $info{ $stock, 'errormsg' } =
134 'A Finnhub API key is required. Get a free key at https://finnhub.io';
135 next;
136 }
137
138 # ---------------------------------------------------------------
139 # Quote: the /quote endpoint returns the price and the unix
140 # timestamp of the last trade. It is the only call required for a
141 # price and date and works for equities and ETFs alike.
142 #
143 # {"c":291.15,"d":-4.48,"dp":-1.5154,"h":297.14,"l":289.62,
144 # "o":296.04,"pc":295.63,"t":1781294400}
145 # c = current price pc = previous close t = unix timestamp
146 # ---------------------------------------------------------------
147 $url = $FINNHUB_URL . 'quote?symbol=' . $stock . '&token=' . $token;
148 $reply = _request( $ua, $url, $max );
149
150 ### Quote reply: $reply->code, $reply->content
151
152 unless ( $reply->code == 200 ) {
153 $info{ $stock, 'success' } = 0;
154 $info{ $stock, 'errormsg' } =
155 $reply->code == 401 ? 'Invalid Finnhub API key'
156 : $reply->code == 429 ? 'Finnhub API rate limit reached'
157 : 'HTTP error ' . $reply->code . ' fetching quote for ' . $stock;
158 next;
159 }
160
161 my $quote = eval { decode_json( $reply->content ) };
162 if ( $@ || !$quote ) {
163 $info{ $stock, 'success' } = 0;
164 $info{ $stock, 'errormsg' } = "Finnhub returned no parseable data for $stock";
165 next;
166 }
167
168 # An unknown symbol returns a price and timestamp of 0.
169 unless ( $quote->{t} && $quote->{c} ) {
170 $info{ $stock, 'success' } = 0;
171 $info{ $stock, 'errormsg' } = "Symbol $stock not found";
172 next;
173 }
174
175 $info{ $stock, 'last' } = $quote->{c};
176 $info{ $stock, 'open' } = $quote->{o} if $quote->{o};
177 $info{ $stock, 'high' } = $quote->{h} if $quote->{h};
178 $info{ $stock, 'low' } = $quote->{l} if $quote->{l};
179 $info{ $stock, 'close' } = $quote->{pc} if $quote->{pc};
180 $info{ $stock, 'net' } = $quote->{d} if defined $quote->{d};
181 $info{ $stock, 'p_change' } = $quote->{dp} if defined $quote->{dp};
182 $info{ $stock, 'method' } = 'finnhub';
183
184 my ( undef, undef, undef, $mday, $mon, $year ) = localtime( $quote->{t} );
185 $quoter->store_date( \%info, $stock,
186 { isodate => sprintf( '%d-%02d-%02d', $year + 1900, $mon + 1, $mday ) } );
187
188 # The quote endpoint does not report a currency. The free tier only
189 # covers US listed securities, so the price is assumed to be in USD.
190 $info{ $stock, 'currency' } = 'USD';
191 $info{ $stock, 'currency_set_by_fq' } = 1;
192
193 $info{ $stock, 'success' } = 1;
194
195 }
196
197 return wantarray() ? %info : \%info;
198
199 }
200
201 1;
202
203 __END__
204
205 =head1 NAME
206
207 Finance::Quote::Finnhub - Obtain quotes from https://finnhub.io
208
209 =head1 SYNOPSIS
210
211 use Finance::Quote;
212
213 $q = Finance::Quote->new('Finnhub', finnhub => {API_KEY => 'your-finnhub-api-key'});
214
215 %info = $q->fetch('finnhub', 'AAPL', 'MSFT');
216
217 =head1 DESCRIPTION
218
219 This module fetches information from L<https://finnhub.io>.
220
221 This module is loaded by default on a Finance::Quote object. It's also possible
222 to load it explicitly by placing "Finnhub" in the argument list to
223 Finance::Quote->new().
224
225 This module provides the "finnhub", "usa", "nyse", and "nasdaq" fetch methods.
226
227 =head1 API_KEY
228
229 L<https://finnhub.io> requires users to register and obtain an API key (token).
230 A free key is available with no credit card and is intended for personal,
231 non-professional use.
232
233 The API key may be set by either providing a module specific hash to
234 Finance::Quote->new as in the above example, or by setting the environment
235 variable FINNHUB_API_KEY.
236
237 =head1 RATE LIMITING
238
239 The free tier permits 60 API calls per minute and this module makes one
240 call per requested symbol. Requests are paced with a sliding window so
241 that batches up to 60 symbols run at full speed and larger batches are
242 slowed just enough to stay within the limit. Holders of a paid key may
243 raise the limit by passing C<< finnhub => { CALLS_PER_MINUTE => N } >> to
244 Finance::Quote->new.
245
246 =head1 LABELS RETURNED
247
248 The following labels may be returned by Finance::Quote::Finnhub:
249 symbol, last, open, high, low, close, net, p_change, date, isodate,
250 currency, method.
251
252 =head1 CAVEATS
253
254 The free Finnhub tier covers US listed equities, ETFs, forex, and
255 cryptocurrency. The trade date is derived from the last trade timestamp
256 returned by the quote endpoint, interpreted in the local timezone.
257
258 The quote endpoint does not report a currency. Because the free tier only
259 covers US listed securities, this module assumes all prices are in USD. Do
260 not rely on the currency for securities priced in another currency.
261
262 Because requests are paced to honour the rate limit, fetching a large list
263 of symbols can take longer than a minute and will block until it completes.
264
265 =cut