Quote/Finnhub.pm

filter: Statementstmt 35.3% 35 / 99 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 75.0% 9 / 12 Podpod 0.0% 0 / 4 totaltotal 25.7% 44 / 171 CC 28 SCAR 52.9
CC
28
Cov
23%
finnhub
380.0
_request
56.0
_throttle
20.0
CRAP 197.5
« Quote/GoldMoney.pm ↑ Summary Quote/BVB.pm »
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 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 5 ▶use JSON qw( decode_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
24 5 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 5 ▶use constant DEBUG => $ENV{DEBUG};
Subroutine BEGIN: called CC=1 SCAR=0.0
27 5 ▶use if DEBUG, 'Smart::Comments', '###';
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 5 our $VERSION = '1.72_02'; # TRIAL VERSION
30  
31 5 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 5 my $MAX_PER_MIN = 60;
39 5 our @finnhub_calls = ();
40  
41 5 our $DISPLAY = 'Finnhub - finnhub.io';
42 5 our $FEATURES = {'API_KEY' => 'registered user API key'};
43 5 our @LABELS = qw/symbol last open high low close net p_change date isodate currency method/;
44 5 our $METHODHASH = {subroutine => \&finnhub,
45 display => $DISPLAY,
46 labels => \@LABELS,
47 features => $FEATURES};
48  
49 10 ▶sub methodinfo {
Subroutine methodinfo: called CC=1 SCAR=0.0
Pod undocumented
50 return (
51 10 finnhub => $METHODHASH,
52 usa => $METHODHASH,
53 nyse => $METHODHASH,
54 nasdaq => $METHODHASH,
55 );
56 }
57  
58 5 ▶sub labels {
Subroutine labels: called CC=1 SCAR=0.0
Pod undocumented
59 5 my %m = methodinfo();
60 5 return map {$_ => [@{$m{$_}{labels}}] } keys %m;
61 }
62  
63 5 ▶sub methods {
Subroutine methods: called CC=1 SCAR=0.0
Pod undocumented
64 5 my %m = methodinfo();
65 5 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 0 ▶sub _throttle {
Subroutine _throttle: not called CC=4 SCAR=30.0
73 0 my $max = shift;
74 0 my $q = $max - 1;
75 0 ▶ if ( $#finnhub_calls >= $q ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($#Finance::Quote::Finnhub::finnhub_calls >= $q) 0 0 0
76 0 my $elapsed = time() - $finnhub_calls[$q];
77 0 ▶ sleep( 60 - $elapsed ) if $elapsed < 60;
Branch: 1 branch
BranchTrueFalseTotal
if $elapsed < 60 0 0 0
78 }
79 0 unshift @finnhub_calls, time();
80 0 ▶ pop @finnhub_calls while $#finnhub_calls > $q;
Branch: 1 branch
BranchTrueFalseTotal
$#Finance::Quote::Finnhub::finnhub_calls > $q and do { pop @Finance::Quote::Finnhub::finnhub_calls } 0 0 0
81 0 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 0 ▶sub _request {
Subroutine _request: not called CC=7 SCAR=40.3
88 0 my ( $ua, $url, $max ) = @_;
89 0 my $reply;
90 0 for ( 1 .. 3 ) {
91 0 _throttle($max);
92 0 $reply = $ua->request( GET $url );
93 0 ▶ last unless $reply->code == 429;
Branch: 1 branch
BranchTrueFalseTotal
unless $reply->code == 429 0 0 0
94  
95 0 my $wait = $reply->header('Retry-After');
96 0 ▶ if ( !defined $wait ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $wait) 0 0 0
97 0 my $reset = $reply->header('X-Ratelimit-Reset');
98 0 ▶ $wait = defined $reset ? $reset - time() : 60;
Branch: 1 branch
BranchTrueFalseTotal
defined $reset ? : 0 0 0
99 }
100 0 ▶ $wait = 1 if $wait < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $wait < 1 0 0 0
101 0 ▶ $wait = 60 if $wait > 60;
Branch: 1 branch
BranchTrueFalseTotal
if $wait > 60 0 0 0
102 0 sleep $wait;
103 }
104 0 return $reply;
105 }
106  
107 0 ▶sub finnhub {
Subroutine finnhub: not called CC=19 SCAR=59.4
Pod undocumented
108  
109 0 my $quoter = shift;
110 0 my @stocks = @_;
111 0 my (%info, $url, $reply);
112 0 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 0 ▶ : $ENV{'FINNHUB_API_KEY'};
Branch: 1 branch
BranchTrueFalseTotal
exists $quoter->{'module_specific_data'}{'finnhub'}{'API_KEY'} ? : 0 0 0
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 0 ▶ : $MAX_PER_MIN;
Branch: 1 branch
BranchTrueFalseTotal
exists $quoter->{'module_specific_data'}{'finnhub'}{'CALLS_PER_MINUTE'} ? : 0 0 0
126  
127 0 foreach my $stock (@stocks) {
128  
129 0 $info{ $stock, 'symbol' } = $stock;
130  
131 0 ▶ if ( !defined $token ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $token) 0 0 0
132 0 $info{ $stock, 'success' } = 0;
133 0 $info{ $stock, 'errormsg' } =
134 'A Finnhub API key is required. Get a free key at https://finnhub.io';
135 0 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 0 $url = $FINNHUB_URL . 'quote?symbol=' . $stock . '&token=' . $token;
148 0 $reply = _request( $ua, $url, $max );
149  
150 ### Quote reply: $reply->code, $reply->content
151  
152 0 ▶ unless ( $reply->code == 200 ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($reply->code == 200) 0 0 0
153 0 $info{ $stock, 'success' } = 0;
154 0 ▶ $info{ $stock, 'errormsg' } =
Branch: 2 branches
BranchTrueFalseTotal
$reply->code == 401 ? : 0 0 0
$reply->code == 429 ? : 0 0 0
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 0 next;
159 }
160  
161 0 my $quote = eval { decode_json( $reply->content ) };
162 0 ▶ if ( $@ || !$quote ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $quote) 0 0 0
Condition0%0/3
$@ or not $quote
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or not $quote
$@ not $quote
Truth table0%0/3
A or not(B)
A= $@B= not $quote
ABresult
1X1
011
000
163 0 $info{ $stock, 'success' } = 0;
164 0 $info{ $stock, 'errormsg' } = "Finnhub returned no parseable data for $stock";
165 0 next;
166 }
167  
168 # An unknown symbol returns a price and timestamp of 0.
169 0 ▶ unless ( $quote->{t} && $quote->{c} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($quote->{"t"} and $quote->{"c"}) 0 0 0
Condition0%0/3
$quote->{"t"} and $quote->{"c"}
!ll&&!rl&&r
000
MC/DC0%0/2
$quote->{"t"} and $quote->{"c"}
$quote->{"t"} $quote->{"c"}
Truth table0%0/3
A and B
A= $quote->{"t"}B= $quote->{"c"}
ABresult
0X0
100
111
170 0 $info{ $stock, 'success' } = 0;
171 0 $info{ $stock, 'errormsg' } = "Symbol $stock not found";
172 0 next;
173 }
174  
175 0 $info{ $stock, 'last' } = $quote->{c};
176 0 ▶ $info{ $stock, 'open' } = $quote->{o} if $quote->{o};
Branch: 1 branch
BranchTrueFalseTotal
if $quote->{"o"} 0 0 0
177 0 ▶ $info{ $stock, 'high' } = $quote->{h} if $quote->{h};
Branch: 1 branch
BranchTrueFalseTotal
if $quote->{"h"} 0 0 0
178 0 ▶ $info{ $stock, 'low' } = $quote->{l} if $quote->{l};
Branch: 1 branch
BranchTrueFalseTotal
if $quote->{"l"} 0 0 0
179 0 ▶ $info{ $stock, 'close' } = $quote->{pc} if $quote->{pc};
Branch: 1 branch
BranchTrueFalseTotal
if $quote->{"pc"} 0 0 0
180 0 ▶ $info{ $stock, 'net' } = $quote->{d} if defined $quote->{d};
Branch: 1 branch
BranchTrueFalseTotal
if defined $quote->{"d"} 0 0 0
181 0 ▶ $info{ $stock, 'p_change' } = $quote->{dp} if defined $quote->{dp};
Branch: 1 branch
BranchTrueFalseTotal
if defined $quote->{"dp"} 0 0 0
182 0 $info{ $stock, 'method' } = 'finnhub';
183  
184 0 my ( undef, undef, undef, $mday, $mon, $year ) = localtime( $quote->{t} );
185 0 $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 0 $info{ $stock, 'currency' } = 'USD';
191 0 $info{ $stock, 'currency_set_by_fq' } = 1;
192  
193 0 $info{ $stock, 'success' } = 1;
194  
195 }
196  
197 0 ▶ return wantarray() ? %info : \%info;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
198  
199 }
200  
201 5 1;
202  
203 __END__
« Quote/GoldMoney.pm ↑ Summary Quote/BVB.pm »