Quote.pm

filter: Statementstmt 62.1% 246 / 396 Branchbran 40.0% 72 / 180 Conditioncond 46.8% 30 / 64 MC/DCmcdc 26.3% 10 / 38 Subroutinesub 71.7% 38 / 53 Podpod 100% 32 / 32 totaltotal 56.0% 428 / 763 CC 123 SCAR 35.8
CC
123
Cov
54%
currency
156.0
fetch
130.7
_convert
90.0
CRAP 36.0
« Quote/ASX.pm ↑ Summary Quote/TMX.pm »
1 #!/usr/bin/perl -w
2 #
3 # vi: set ts=2 sw=2 noai ic showmode showmatch:
4 #
5 # Copyright (C) 1998, Dj Padzensky <djpadz@padz.net>
6 # Copyright (C) 1998, 1999 Linas Vepstas <linas@linas.org>
7 # Copyright (C) 2000, Yannick LE NY <y-le-ny@ifrance.com>
8 # Copyright (C) 2000, Paul Fenwick <pjf@cpan.org>
9 # Copyright (C) 2000, Brent Neal <brentn@users.sourceforge.net>
10 #
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program; if not, write to the Free Software
23 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 # 02110-1301, USA
25 #
26 #
27 # This code derived from Padzensky's work on package Finance::YahooQuote,
28 # but extends its capabilites to encompas a greater number of data sources.
29 #
30 # This code was developed as part of GnuCash <http://www.gnucash.org/>
31  
32 package Finance::Quote;
33  
34 52 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 52 ▶use constant DEBUG => $ENV{DEBUG};
Subroutine BEGIN: called CC=1 SCAR=0.0
37 52 ▶use if DEBUG, 'Smart::Comments', '###';
Subroutine BEGIN: called CC=1 SCAR=0.0
38  
39 52 ▶use Module::Load;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 52 ▶use Exporter ();
Subroutine BEGIN: called CC=1 SCAR=0.0
41 52 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 52 ▶use Finance::Quote::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 52 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 52 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 52 ▶use JSON qw( decode_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
46  
47 52 ▶use vars qw/@ISA @EXPORT @EXPORT_OK @EXPORT_TAGS
Subroutine BEGIN: called CC=1 SCAR=0.0
48 $TIMEOUT @MODULES %MODULES %METHODS $AUTOLOAD
49 52 @CURRENCY_RATES_MODULES $USE_EXPERIMENTAL_UA/;
50  
51 52 our $VERSION = '1.72'; # VERSION
52  
53 52 @CURRENCY_RATES_MODULES = qw/
54 AlphaVantage
55 CurrencyFreaks
56 ECB
57 FinanceAPI
58 Fixer
59 Frankfurter
60 OpenExchange
61 TwelveData
62 UniRate
63 YahooJSON
64 /;
65  
66 52 @MODULES = qw/
67 ASEGR
68 ASX
69 AlphaVantage
70 BSEIndia
71 BorsaItaliana
72 Bourso
73 BVB
74 CSE
75 Comdirect
76 Consorsbank
77 Currencies
78 Deka
79 FinanceAPI
80 Finanzpartner
81 Finnhub
82 Fondsweb
83 Fool
84 FTfunds
85 GoldMoney
86 GoogleWeb
87 IndiaMutual
88 MarketWatch
89 MorningstarJP
90 NPSNAV
91 NSEIndia
92 NZX
93 OnVista
94 SIX
95 Sinvestor
96 StockData
97 Stooq
98 SwissFundData
99 TesouroDireto
100 TMX
101 Tradegate
102 TreasuryDirect
103 TSP
104 TwelveData
105 Union
106 USBonds
107 XETRA
108 YahooJSON
109 YahooWeb
110 ZA
111 /;
112  
113 52 @ISA = qw/Exporter/;
114 52 @EXPORT = ();
115 52 @EXPORT_OK = qw/asx currency_lookup/;
116 52 @EXPORT_TAGS = ( all => [@EXPORT_OK]);
117  
118 52 $USE_EXPERIMENTAL_UA = 0;
119  
120 ################################################################################
121 #
122 # Private Class Methods
123 #
124 ################################################################################
125 # Autoload method for obsolete methods. This also allows people to
126 # call methods that objects export without having to go through fetch.
127  
128 0 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: not called CC=2 SCAR=14.2
129 0 my $method = $AUTOLOAD;
130 0 (my $name = $method) =~ s/.*:://;
131  
132 # Force the dummy object (and hence default methods) to be loaded.
133 0 _dummy();
134  
135 0 ▶ if (exists($METHODS{$name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Finance::Quote::METHODS{$name}) 0 0 0
136 52 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
137
138 0 ▶ *$method = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
139 0 ▶ my $this = ref($_[0]) ? shift : _dummy();
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 0 0
140 0 $this->fetch($name, @_);
141 0 };
142  
143 0 return &$method;
144 }
145  
146 0 carp "$AUTOLOAD does not refer to a known method.";
147 }
148  
149 # Dummy destroy function to avoid AUTOLOAD catching it.
150 0 ▶sub DESTROY { return; }
Subroutine DESTROY: not called CC=1 SCAR=6.9
151  
152 # _convert (private object method)
153 #
154 # This function converts between one currency and another. It expects
155 # to receive a hashref to the information, a reference to a list
156 # of the stocks to be converted, and a reference to a list of fields
157 # that conversion should apply to.
158  
159 {
160 52 my %conversion; # Conversion lookup table.
161  
162 0 ▶ sub _convert {
Subroutine _convert: not called CC=9 SCAR=45.0
163 0 my $this = shift;
164 0 my $info = shift;
165 0 my $stocks = shift;
166 0 my $convert_fields = shift;
167 0 my $new_currency = $this->{"currency"};
168  
169 # Skip all this unless they actually want conversion.
170 0 ▶ return unless $new_currency;
Branch: 1 branch
BranchTrueFalseTotal
unless $new_currency 0 0 0
171  
172 0 foreach my $stock (@$stocks) {
173 0 my $currency;
174  
175 # Skip stocks that don't have a currency.
176 0 ▶ next unless ($currency = $info->{$stock,"currency"});
Branch: 1 branch
BranchTrueFalseTotal
unless $currency = $$info{join $;, $stock, "currency"} 0 0 0
177  
178 # Skip if it's already in the same currency.
179 0 ▶ next if ($currency eq $new_currency);
Branch: 1 branch
BranchTrueFalseTotal
if $currency eq $new_currency 0 0 0
180  
181 # Lookup the currency conversion if we haven't
182 # already.
183 0 ▶ unless (exists $conversion{$currency,$new_currency}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $conversion{join $;, $currency, $new_currency}) 0 0 0
184 0 $conversion{$currency,$new_currency} =
185 $this->currency($currency,$new_currency);
186 }
187  
188 # Make sure we have a reasonable currency conversion.
189 # If we don't, mark the stock as bad.
190 0 ▶ unless ($conversion{$currency,$new_currency}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($conversion{join $;, $currency, $new_currency}) 0 0 0
191 0 $info->{$stock,"success"} = 0;
192 0 $info->{$stock,"errormsg"} =
193 "Currency conversion failed.";
194 0 next;
195 }
196  
197 # Okay, we have clean data. Convert it. Ideally
198 # we'd like to just *= entire fields, but
199 # unfortunately some things (like ranges,
200 # capitalisation, etc) don't take well to that.
201 # Hence we pull out any numbers we see, convert
202 # them, and stick them back in. That's pretty
203 # yucky, but it works.
204  
205 0 foreach my $field (@$convert_fields) {
206 0 ▶ next unless (defined $info->{$stock,$field});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$info{join $;, $stock, $field} 0 0 0
207  
208 0 $info->{$stock,$field} = $this->scale_field($info->{$stock,$field},$conversion{$currency,$new_currency});
209 }
210  
211 # Set the new currency.
212 0 $info->{$stock,"currency"} = $new_currency;
213 }
214 }
215 }
216  
217 # =======================================================================
218 # _dummy (private function)
219 #
220 # _dummy returns a Finance::Quote object. I'd really rather not have
221 # this, but to maintain backwards compatibility we hold on to it.
222 {
223 52 my $dummy_obj;
224 6 ▶ sub _dummy {
Subroutine _dummy: called CC=2 SCAR=7.2
225 6 ▶ return $dummy_obj ||= Finance::Quote->new;
Condition66%2/3
$dummy_obj ||= "Finance::Quote"->new
l!l&&r!l&&!r
510
MC/DC0%0/2
$dummy_obj ||= "Finance::Quote"->new
$dummy_obj "Finance::Quote"->new
Truth table66%2/3
A ||= B
A= $dummy_objB= "Finance::Quote"->new
ABresult
1X1
011
000
226 }
227 }
228  
229 # _load_module (private class method)
230 # _load_module loads a module(s) and registers its various methods for
231 # use.
232  
233 52 ▶sub _load_modules {
Subroutine _load_modules: called CC=7 SCAR=19.5
234 14 my $class = shift;
235 14 ▶ my $baseclass = ref $class || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
1400
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
236  
237 14 my @modules = @_;
238  
239 # Go to each module and use them. Also record what methods
240 # they support and enter them into the %METHODS hash.
241  
242 14 foreach my $module (@modules) {
243 616 my $modpath = "${baseclass}::${module}";
244 616 ▶ unless (defined($MODULES{$modpath})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Finance::Quote::MODULES{$modpath}) 220 396 616
245  
246 220 eval {
247 220 load $modpath;
248 220 $MODULES{$modpath} = 1;
249  
250 220 my %methodhash = $modpath->methods;
251 220 my %labelhash = $modpath->labels;
252 220 ▶ my $curr_fields_func = $modpath->can("currency_fields") || \&default_currency_fields;
Condition100%2/2
$modpath->can('currency_fields') || \&Finance::Quote::default_currency_fields
l!l
5215
MC/DC100%1/1
$modpath->can('currency_fields') || \&Finance::Quote::default_currency_fields
$modpath->can('currency_fields')
Truth table100%2/2
A
A= $modpath->can('currency_fields')
Aresult
11
00
253 220 my @currency_fields = &$curr_fields_func;
254 220 my %seen;
255 220 @currency_fields = grep {!$seen{$_}++} @currency_fields;
256  
257 220 foreach my $method (keys %methodhash) {
258 505 push (@{$METHODS{$method}},
259 { name => $module,
260 modpath => $modpath,
261 function => $methodhash{$method},
262 505 labels => $labelhash{$method},
263 currency_fields => \@currency_fields});
264 }
265 };
266 220 ▶ carp $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 220 220
267 }
268 }
269 }
270  
271 # _smart_compare (private method function)
272 #
273 # This function compares values where the method depends on the
274 # type of the parameters.
275 # val1, val2
276 # scalar,scaler - test for substring match
277 # scalar,regex - test val1 against val2 regex
278 # array,scalar - return true if any element of array substring matches scalar
279 # array,regex - return true if any element of array matches regex
280 675 ▶sub _smart_compare {
Subroutine _smart_compare: called CC=4 SCAR=19.1
281 675 my ($val1, $val2) = @_;
282
283 675 ▶ if ( ref $val1 eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val1 eq 'ARRAY') { } 0 675 675
284 0 ▶ if ( ref $val2 eq 'Regexp' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val2 eq 'Regexp') { } 0 0 0
285 0 my @r = grep {$_ =~ $val2} @$val1;
286 0 return @r > 0;
287 }
288 else {
289 0 my @r = grep {$_ =~ /$val2/} @$val1;
290 0 return @r > 0;
291 }
292 }
293 else {
294 675 ▶ if ( ref $val2 eq 'Regexp' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val2 eq 'Regexp') { } 337 338 675
295 337 return $val1 =~ $val2;
296 }
297 else {
298 338 return index($val1, $val2) > -1
299 }
300 }
301 }
302  
303 # This is a list of fields that will be automatically converted during
304 # currency conversion. If a module provides a currency_fields()
305 # function then that list will be used instead.
306  
307 216 ▶sub get_default_currency_fields {
Subroutine get_default_currency_fields: called CC=1 SCAR=0.0
Pod documented
308 216 return qw/last high low net bid ask close open day_range year_range
309 eps div cap nav price/;
310 }
311  
312 2 ▶sub get_default_timeout {
Subroutine get_default_timeout: called CC=1 SCAR=0.0
Pod documented
313 2 return $TIMEOUT;
314 }
315  
316 # get_methods returns a list of sources which can be passed to fetch to
317 # obtain information.
318  
319 1 ▶sub get_methods {
Subroutine get_methods: called CC=2 SCAR=7.2
Pod documented
320 # Create a dummy object to ensure METHODS is populated
321 1 my $t = Finance::Quote->new();
322 1 ▶ return(wantarray ? keys %METHODS : [keys %METHODS]);
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 0 1
323 }
324  
325 # return hash:
326 #
327 # quote_methods => hash of
328 # method_name => array of module names
329 # quote_modules => hash of
330 # module_name => array of parameters
331 # currency_modules => hash of
332 # module_name => array of parameters
333 #
334 # {
335 # 'quote_methods' => {'group' => ['module', 'module'], ...},
336 # 'quote_modules' => {'abc' => ['API_KEY'], ...},
337 # 'currency_modules' => {'xyz' => [], 'lmn' => ['USER_NAME', 'API_KEY']},
338 # }
339  
340 1 ▶sub get_features {
Subroutine get_features: called CC=4 SCAR=13.9
Pod documented
341 # Create a dummy object to ensure METHODS is populated
342 1 my $t = Finance::Quote->new(currency_rates => {order => \@CURRENCY_RATES_MODULES});
343 1 my $baseclass = ref $t;
344  
345 my %feature = (
346 63 'quote_methods' => {map {$_, [map {$_->{name}} @{$METHODS{$_}}]} keys %METHODS},
347 44 'quote_modules' => {map {$_, []} @MODULES},
348 1 'currency_modules' => {map {$_, []} @CURRENCY_RATES_MODULES},
349 );
350  
351 1 my %mods = ('quote_modules' => $baseclass,
352 'currency_modules' => "${baseclass}::CurrencyRates");
353  
354 1 ▶ while (my ($field, $base) = each %mods) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %mods) 2 1 3
355 2 foreach my $name (keys %{$feature{$field}}) {
356 54 my $modpath = "${base}::${name}";
357  
358 54 ▶ if ($modpath->can("parameters")) {
Branch: 1 branch
BranchTrueFalseTotal
if ($modpath->can("parameters")) 7 47 54
359 7 push (@{$feature{$field}->{$name}}, $modpath->parameters());
360 }
361 }
362 }
363  
364 1 return %feature;
365 }
366  
367 # =======================================================================
368 # new (public class method)
369 #
370 # Returns a new Finance::Quote object.
371 #
372 # Arguments ::
373 # - zero or more module names from the Finance::Quote::get_sources list
374 # - zero or more named parameters, passes as name => value
375 #
376 # Named Parameters ::
377 # - timeout # timeout in seconds for web requests
378 # - failover # boolean value indicating if failover is acceptable
379 # - fetch_currency # currency code for fetch results
380 # - required_labels # array of required labels in fetch results
381 # - <module-name> # hash specific to various Finance::Quote modules
382 #
383 # new() # default constructor
384 # new('a', 'b') # load only modules a and b
385 # new(timeout => 30) # load all default modules, set timeout
386 # new('a', fetch_currency => 'X') # load only module a, use currency X for results
387 # new('z' => {API_KEY => 'K'}) # load all modules, pass hash to module z constructor
388 # new('z', 'z' => {API_KEY => 'K'}) # load only module z and pass hash to its constructor
389 #
390 # Enivornment Variables ::
391 # - FQ_LOAD_QUOTELET # if no modules named in argument list, use ones in this variable
392 #
393 # Return Value ::
394 # - Finanace::Quote object
395  
396 14 ▶sub new {
Subroutine new: called CC=21 SCAR=38.2
Pod documented
397 # Create and bless object
398 14 my $self = shift;
399 14 ▶ my $class = ref($self) || $self;
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
0140
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
400  
401 14 my $this = {};
402 14 bless $this, $class;
403  
404 # To add a named parameter:
405 # 0. Document it in the POD for new
406 # 1. Add a default value for $this->{object-name}
407 # 2. Add the 'user-visible-name' => [type, object-name] to %named_parameter
408  
409 # Check for FQ_CURRENCY - preferred currency module
410 # Set to AlphaVantage if not set or not in @CURRENCY_RATES_MODULES
411 14 my $CURRENCY_MODULE;
412 14 ▶ if (!$ENV{FQ_CURRENCY}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ENV{'FQ_CURRENCY'}) { } 14 0 14
413 14 $CURRENCY_MODULE='AlphaVantage';
414 } else {
415 0 ▶ if ( grep( /^$ENV{FQ_CURRENCY}$/, @CURRENCY_RATES_MODULES ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep /^$ENV{'FQ_CURRENCY'}$/, @Finance::Quote::CURRENCY_RATES_MODULES) { } 0 0 0
416 $CURRENCY_MODULE=$ENV{FQ_CURRENCY}
417 0 } else {
418 0 $CURRENCY_MODULE='AlphaVantage';
419 }
420 }
421  
422 # Default values
423 14 $this->{FAILOVER} = 1;
424 14 $this->{REQUIRED} = [];
425 14 ▶ $this->{TIMEOUT} = $TIMEOUT if defined($TIMEOUT);
Branch: 1 branch
BranchTrueFalseTotal
if defined $Finance::Quote::TIMEOUT 2 12 14
426 14 $this->{currency_rates} = {order => [$CURRENCY_MODULE]};
427  
428 # Sort out arguments
429 14 my %named_parameter = (timeout => ['', 'TIMEOUT'],
430 failover => ['', 'FAILOVER'],
431 fetch_currency => ['', 'currency'],
432 required_labels => ['ARRAY', 'REQUIRED'],
433 currency_rates => ['HASH', 'currency_rates']);
434  
435 14 $this->{module_specific_data} = {};
436 14 my @load_modules = ();
437  
438 14 ▶ for (my $i = 0; $i < @_; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @_) 5 14 19
439 5 ▶ if (exists $named_parameter{$_[$i]}) {
Branch: 3 branches
BranchTrueFalseTotal
if (exists $named_parameter{$_[$i]}) { } 5 0 5
elsif ($i + 1 < @_ and ref $_[$i + 1] eq 'HASH') { } 0 0 0
elsif ($_[$i] eq '-defaults') { } 0 0 0
440 5 ▶ die "missing value for named parameter $_[$i]" if $i + 1 == @_;
Branch: 1 branch
BranchTrueFalseTotal
if $i + 1 == @_ 0 5 5
441 5 ▶ die "unexpect type for value of named parameter $_[$i]" if ref $_[$i+1] ne $named_parameter{$_[$i]}[0];
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[$i + 1] ne $named_parameter{$_[$i]}[0] 0 5 5
442  
443 5 $this->{$named_parameter{$_[$i]}[1]} = $_[$i+1];
444 5 $i += 1;
445 }
446 ▶ elsif ($i + 1 < @_ and ref $_[$i+1] eq 'HASH') {
Condition0%0/3
$i + 1 < @_ and ref $_[$i + 1] eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
$i + 1 < @_ and ref $_[$i + 1] eq "HASH"
$i + 1 < @_ ref $_[$i + 1] eq "HASH"
Truth table0%0/3
A and B
A= $i + 1 < @_B= ref $_[$i + 1] eq "HASH"
ABresult
0X0
100
111
447 0 $this->{module_specific_data}->{$_[$i]} = $_[$i+1];
448 0 $i += 1;
449 }
450 elsif ($_[$i] eq '-defaults') {
451 0 push (@load_modules, @MODULES);
452 }
453 else {
454 0 push (@load_modules, $_[$i]);
455 }
456 }
457  
458 # Honor FQ_LOAD_QUOTELET if @load_modules is empty
459 14 ▶ if ($ENV{FQ_LOAD_QUOTELET} and !@load_modules) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ENV{'FQ_LOAD_QUOTELET'} and not @load_modules) { } 0 14 14
elsif (@load_modules == 0) { } 14 0 14
Condition33%1/3
$ENV{"FQ_LOAD_QUOTELET"} and not @load_modules
!ll&&!rl&&r
1400
MC/DC0%0/2
$ENV{"FQ_LOAD_QUOTELET"} and not @load_modules
$ENV{"FQ_LOAD_QUOTELET"} not @load_modules
Truth table33%1/3
A and not(B)
A= $ENV{"FQ_LOAD_QUOTELET"}B= not @load_modules
ABresult
0X0
100
111
460 0 @load_modules = split(' ',$ENV{FQ_LOAD_QUOTELET});
461 0 ▶ if ($load_modules[0] eq '-defaults') {
Branch: 1 branch
BranchTrueFalseTotal
if ($load_modules[0] eq "-defaults") 0 0 0
462 0 shift @load_modules;
463 0 push(@load_modules, @MODULES);
464 }
465 }
466 elsif (@load_modules == 0) {
467 14 push(@load_modules, @MODULES);
468 }
469  
470 14 $this->_load_modules(@load_modules);
471  
472 # Load the currency rate methods
473 14 my %currency_check = map { $_ => 1 } @CURRENCY_RATES_MODULES;
474 14 $this->{currency_rate_method} = [];
475 14 foreach my $method (@{$this->{currency_rates}->{order}}) {
476 23 ▶ unless (defined($currency_check{$method})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $currency_check{$method}) 0 23 23
477 0 carp "Unknown curreny rates method: $method";
478 0 return;
479 }
480  
481 23 my $method_path = "${class}::CurrencyRates::${method}";
482 23 eval {
483 23 autoload $method_path;
484 23 ▶ my $args = exists $this->{currency_rates}->{lc($method)} ? $this->{currency_rates}->{lc($method)} : {};
Branch: 1 branch
BranchTrueFalseTotal
exists $this->{'currency_rates'}{lc $method} ? : 0 23 23
485 23 my $rate = $method_path->new($args);
486 23 ▶ die unless defined $rate;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rate 2 21 23
487
488 21 push(@{$this->{currency_rate_method}}, $rate);
489 };
490  
491 23 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 21 23
492 2 next;
493 }
494 }
495  
496 14 return $this;
497 }
498  
499 1 ▶sub set_default_timeout {
Subroutine set_default_timeout: called CC=1 SCAR=0.0
Pod documented
500 1 $TIMEOUT = shift;
501 }
502  
503 ################################################################################
504 #
505 # Private Object Methods
506 #
507 ################################################################################
508  
509 # _require_test (private object method)
510 #
511 # This function takes an array. It returns true if all required
512 # labels appear in the arrayref. It returns false otherwise.
513 #
514 # This function could probably be made more efficient.
515  
516 0 ▶sub _require_test {
Subroutine _require_test: not called CC=4 SCAR=30.0
517 0 my $this = shift;
518 0 my %available;
519 0 @available{@_} = (); # Ooooh, hash-slice. :)
520 0 my @required = @{$this->{REQUIRED}};
521 0 ▶ return 1 unless @required;
Branch: 1 branch
BranchTrueFalseTotal
unless @required 0 0 0
522 0 ▶ for (my $i = 0; $i < @required; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @required) 0 0 0
523 0 ▶ return 0 unless exists $available{$required[$i]};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $available{$required[$i]} 0 0 0
524 }
525 0 return 1;
526 }
527  
528 ################################################################################
529 #
530 # Public Object Methods
531 #
532 ################################################################################
533  
534 # If $str ends with a B like "20B" or "1.6B" then expand it as billions like
535 # "20000000000" or "1600000000".
536 #
537 # This is done with string manipulations so floating-point rounding doesn't
538 # produce spurious digits for values like "1.6" which aren't exactly
539 # representable in binary.
540 #
541 # Is "B" for billions the only abbreviation from Yahoo?
542 # Could extend and rename this if there's also millions or thousands.
543 #
544 # For reference, if the value was just for use within perl then simply
545 # substituting to exponential "1.5e9" might work. But expanding to full
546 # digits seems a better idea as the value is likely to be printed directly
547 # as a string.
548 4 ▶sub B_to_billions {
Subroutine B_to_billions: called CC=2 SCAR=7.0
Pod documented
549 4 my ($self,$str) = @_;
550  
551 # B_to_billions() $str
552 4 ▶ if ($str =~ s/B$//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ s/B$//i) 4 0 4
553 4 $str = $self->decimal_shiftup ($str, 9);
554 }
555 4 return $str;
556 }
557  
558 # $str is a number like "123" or "123.45"
559 # return it with the decimal point moved $shift places to the right
560 # must have $shift>=1
561 # eg. decimal_shiftup("123",3) -> "123000"
562 # decimal_shiftup("123.45",1) -> "1234.5"
563 # decimal_shiftup("0.25",1) -> "2.5"
564 #
565 19 ▶sub decimal_shiftup {
Subroutine decimal_shiftup: called CC=3 SCAR=11.0
Pod documented
566 19 my ($self, $str, $shift) = @_;
567  
568 # delete decimal point and set $after to count of chars after decimal.
569 # Leading "0" as in "0.25" is deleted too giving "25" so as not to end up
570 # with something that might look like leading 0 for octal.
571 19 ▶ my $after = ($str =~ s/(?:^0)?\.(.*)/$1/ ? length($1) : 0);
Branch: 1 branch
BranchTrueFalseTotal
$str =~ s/(?:^0)?\.(.*)/$1/ ? : 14 5 19
572  
573 19 $shift -= $after;
574 # now $str is an integer and $shift is relative to the end of $str
575  
576 19 ▶ if ($shift >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shift >= 0) { } 12 7 19
577 # moving right, eg. "1234" becomes "12334000"
578 12 return $str . ('0' x $shift); # extra zeros appended
579 } else {
580 # negative means left, eg. "12345" becomes "12.345"
581 # no need to prepend zeros since demanding initial $shift>=1
582 7 substr ($str, $shift,0, '.'); # new '.' at shifted spot from end
583 7 return $str;
584 }
585 }
586  
587 # =======================================================================
588 # fetch (public object method)
589 #
590 # Fetch is a wonderful generic fetcher. It takes a method and stuff to
591 # fetch. It's a nicer interface for when you have a list of stocks with
592 # different sources which you wish to deal with.
593 0 ▶sub fetch {
Subroutine fetch: not called CC=12 SCAR=48.7
Pod documented
594 0 ▶ my $this = ref($_[0]) ? shift : _dummy();
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 0 0
595  
596 0 my $method = lc(shift);
597 0 my @stocks = @_;
598  
599 0 ▶ unless (exists $METHODS{$method}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $Finance::Quote::METHODS{$method}) 0 0 0
600 0 carp "Undefined fetch-method $method passed to ".
601 "Finance::Quote::fetch";
602 0 return;
603 }
604  
605 {
606 # Setting no critic to avoid Stricture disabled failure
607 # in t/04-critic.t
608 ## no critic
609 0 ▶ no strict 'vars';
Subroutine BEGIN: called CC=1 SCAR=0.2
610 0 ▶ our $VERSION = '0.00' unless defined $VERSION;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $VERSION 0 0 0
611 ## use critic
612 0 ▶ unless ($ENV{"FQ_NOCOUNT"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ENV{"FQ_NOCOUNT"}) 0 0 0
613 # Temporary Counting - not concerned about return code
614 0 my $COUNT_URL =
615 'http://www.panix.com/~hd-fxsts/finance-quote.html?fqversion=' . $VERSION . '&fqmethod=' . $method;
616 0 my $count_ua = LWP::UserAgent->new(timeout => 10);
617 0 my $count_response = $count_ua->head($COUNT_URL);
618  
619 ### COUNT_URL: $COUNT_URL
620 ### Code: $count_response->code
621 }
622 }
623  
624 # Failover code. This steps through all available methods while
625 # we still have failed stocks to look-up. This loop only
626 # runs a single time unless FAILOVER is defined.
627 0 my %returnhash = ();
628  
629 0 foreach my $methodinfo (@{$METHODS{$method}}) {
630 0 my $funcref = $methodinfo->{"function"};
631 0 ▶ next unless $this->_require_test(@{$methodinfo->{"labels"}});
Branch: 1 branch
BranchTrueFalseTotal
unless $this->_require_test(@{$$methodinfo{"labels"};}) 0 0 0
632 0 my @failed_stocks = ();
633 0 %returnhash = (%returnhash,&$funcref($this,@stocks));
634  
635 0 foreach my $stock (@stocks) {
636 push(@failed_stocks,$stock)
637 0 ▶ unless ($returnhash{$stock,"success"});
Branch: 1 branch
BranchTrueFalseTotal
unless $returnhash{join $;, $stock, "success"} 0 0 0
638 }
639  
640 $this->_convert(\%returnhash,\@stocks,
641 0 $methodinfo->{"currency_fields"});
642  
643 0 ▶ last unless $this->{FAILOVER};
Branch: 1 branch
BranchTrueFalseTotal
unless $this->{"FAILOVER"} 0 0 0
644 0 ▶ last unless @failed_stocks;
Branch: 1 branch
BranchTrueFalseTotal
unless @failed_stocks 0 0 0
645 0 @stocks = @failed_stocks;
646 }
647  
648 0 ▶ return wantarray() ? %returnhash : \%returnhash;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
649 }
650  
651 3 ▶sub get_failover {
Subroutine get_failover: called CC=1 SCAR=0.0
Pod documented
652 3 my $self = shift;
653 3 return $self->{FAILOVER};
654 }
655  
656 3 ▶sub get_fetch_currency {
Subroutine get_fetch_currency: called CC=1 SCAR=0.0
Pod documented
657 3 my $self = shift;
658 3 return $self->{currency};
659 }
660  
661 3 ▶sub get_required_labels {
Subroutine get_required_labels: called CC=1 SCAR=0.0
Pod documented
662 3 my $self = shift;
663 3 return $self->{REQUIRED};
664 }
665  
666 4 ▶sub get_timeout {
Subroutine get_timeout: called CC=1 SCAR=0.0
Pod documented
667 4 my $self = shift;
668 4 return $self->{TIMEOUT};
669 }
670  
671 2 ▶sub get_user_agent {
Subroutine get_user_agent: called CC=4 SCAR=14.1
Pod documented
672 2 my $this = shift;
673  
674 2 ▶ return $this->{UserAgent} if $this->{UserAgent};
Branch: 1 branch
BranchTrueFalseTotal
if $this->{"UserAgent"} 1 1 2
675  
676 1 my $ua;
677  
678 1 ▶ if ($USE_EXPERIMENTAL_UA) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Finance::Quote::USE_EXPERIMENTAL_UA) { } 0 1 1
679 0 $ua = Finance::Quote::UserAgent->new;
680 } else {
681 1 $ua = LWP::UserAgent->new;
682 }
683  
684 1 ▶ $ua->timeout($this->{TIMEOUT}) if defined($this->{TIMEOUT});
Branch: 1 branch
BranchTrueFalseTotal
if defined $this->{"TIMEOUT"} 1 0 1
685 1 $ua->env_proxy;
686  
687 1 $this->{UserAgent} = $ua;
688  
689 1 return $ua;
690 }
691  
692 11 ▶sub isoTime {
Subroutine isoTime: called CC=12 SCAR=26.1
Pod documented
693 11 my ($self,$timeString) = @_ ;
694 11 $timeString =~ tr/ //d ;
695 11 $timeString = uc $timeString ;
696 11 my $retTime = "00:00"; # return zero time if unparsable input
697 11 ▶ if ($timeString=~m/^(\d+)[\.:UH](\d+) *(AM|am|PM|pm)?/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timeString =~ /^(\d+)[\.:UH](\d+) *(AM|am|PM|pm)?/) 11 0 11
698 11 my ($hours,$mins)= ($1-0,$2-0) ;
699 11 ▶ $hours-=12 if ($hours==12 && $3 && ($3 =~ /AM/i));
Branch: 1 branch
BranchTrueFalseTotal
if $hours == 12 and $3 and $3 =~ /AM/i 0 11 11
Condition66%4/6
$hours == 12 and $3 and $3 =~ /AM/i
!ll&&!rl&&r
920
$hours == 12 and $3
!ll&&!rl&&r
902
MC/DC0%0/3
$hours == 12 and $3 and $3 =~ /AM/i
$hours == 12 $3 $3 =~ /AM/i
Truth table50%2/4
A and B and C
A= $hours == 12B= $3C= $3 =~ /AM/i
ABCresult
0XX0
10X0
1100
1111
700 11 ▶ $hours+=12 if ($3 && ($3 =~ /PM/i) && ($hours != 12));
Branch: 1 branch
BranchTrueFalseTotal
if $3 and $3 =~ /PM/i and $hours != 12 3 8 11
Condition100%6/6
$3 and $3 =~ /PM/i and $hours != 12
!ll&&!rl&&r
623
$3 and $3 =~ /PM/i
!ll&&!rl&&r
425
MC/DC100%3/3
$3 and $3 =~ /PM/i and $hours != 12
$3 $3 =~ /PM/i $hours != 12
Truth table100%4/4
A and B and C
A= $3B= $3 =~ /PM/iC= $hours != 12
ABCresult
0XX0
10X0
1100
1111
701 11 ▶ if ($hours>=0 && $hours<=23 && $mins>=0 && $mins<=59 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hours >= 0 and $hours <= 23 and $mins >= 0 and $mins <= 59) 10 1 11
Condition44%4/9
$hours >= 0 and $hours <= 23 and $mins >= 0 and $mins <= 59
!ll&&!rl&&r
0110
$hours >= 0 and $hours <= 23 and $mins >= 0
!ll&&!rl&&r
0011
$hours >= 0 and $hours <= 23
!ll&&!rl&&r
0011
MC/DC25%1/4
$hours >= 0 and $hours <= 23 and $mins >= 0 and $mins <= 59
$hours >= 0 $hours <= 23 $mins >= 0 $mins <= 59
Truth table40%2/5
A and B and C and D
A= $hours >= 0B= $hours <= 23C= $mins >= 0D= $mins <= 59
ABCDresult
0XXX0
10XX0
110X0
11100
11111
702 10 $retTime = sprintf ("%02d:%02d", $hours, $mins) ;
703 }
704 }
705 11 return $retTime;
706 }
707  
708 1 ▶sub set_failover {
Subroutine set_failover: called CC=1 SCAR=0.0
Pod documented
709 1 my $self = shift;
710 1 $self->{FAILOVER} = shift;
711 }
712  
713 1 ▶sub set_fetch_currency {
Subroutine set_fetch_currency: called CC=1 SCAR=0.0
Pod documented
714 1 my $self = shift;
715 1 $self->{currency} = shift;
716 }
717  
718 1 ▶sub set_required_labels {
Subroutine set_required_labels: called CC=1 SCAR=0.0
Pod documented
719 1 my $self = shift;
720 1 $self->{REQUIRED} = shift;
721 }
722  
723 1 ▶sub set_timeout {
Subroutine set_timeout: called CC=1 SCAR=0.0
Pod documented
724 1 my $self = shift;
725 1 $self->{TIMEOUT} = shift;
726 }
727  
728 # =======================================================================
729 # store_date (public object method)
730 #
731 # Given the various pieces of a date, this functions figure out how to
732 # store them in both the pre-existing US date format (mm/dd/yyyy), and
733 # also in the ISO date format (yyyy-mm-dd). This function expects to
734 # be called with the arguments:
735 #
736 # (inforef, symbol_name, data_hash)
737 #
738 # The components of date hash can be any of:
739 #
740 # usdate - A date in mm/dd/yy or mm/dd/yyyy
741 # eurodate - A date in dd/mm/yy or dd/mm/yyyy
742 # isodate - A date in yy-mm-dd or yyyy-mm-dd, yyyy/mm/dd, yyyy.mm.dd, or yyyymmdd
743 # year - The year in yyyy
744 # month - The month in mm or mmm format (i.e. 07 or Jul)
745 # day - The day
746 # today - A flag to indicate todays date should be used.
747 #
748 # The separator for the *date forms is ignored. It can be any
749 # non-alphanumeric character. Any combination of year, month, and day
750 # values can be provided. Missing fields are filled in based upon
751 # today's date.
752 #
753 sub store_date
754 13 ▶{
Subroutine store_date: called CC=18 SCAR=29.2
Pod documented
755 13 my $this = shift;
756 13 my $inforef = shift;
757 13 my $symbol = shift;
758 13 my $piecesref = shift;
759  
760 13 my ($year, $month, $day, $this_month, $year_specified);
761 13 my %mnames = (jan => 1, feb => 2, mar => 3, apr => 4, may => 5, jun => 6,
762 jul => 7, aug => 8, sep => 9, oct =>10, nov =>11, dec =>12);
763  
764 ### store_date symbol: $symbol
765 ### store_date pieces: $piecesref
766  
767 # Default to today's date.
768 13 ($month, $day, $year) = (localtime())[4,3,5];
769 13 $month++;
770 13 $year += 1900;
771 13 $this_month = $month;
772 13 $year_specified = 0;
773  
774 # Process the inputs
775 13 ▶ if ((defined $piecesref->{isodate}) && ($piecesref->{isodate})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $piecesref->{"isodate"} and $piecesref->{"isodate"}) 3 10 13
Condition66%2/3
defined $piecesref->{"isodate"} and $piecesref->{"isodate"}
!ll&&!rl&&r
1003
MC/DC50%1/2
defined $piecesref->{"isodate"} and $piecesref->{"isodate"}
defined $piecesref->{"isodate"} $piecesref->{"isodate"}
Truth table66%2/3
A and B
A= defined $piecesref->{"isodate"}B= $piecesref->{"isodate"}
ABresult
0X0
100
111
776 3 ▶ if ($piecesref->{isodate} =~ /^([0-9]{4})([0-9]{2})([0-9]{2})$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($piecesref->{'isodate'} =~ /^([0-9]{4})([0-9]{2})([0-9]{2})$/) { } 0 3 3
777 0 ($year, $month, $day) = ($1, $2, $3);
778 }
779 else {
780 3 ($year, $month, $day) = ($piecesref->{isodate} =~ m|([0-9]{4})\W+(\w+)\W+(\w+)|);
781 }
782  
783 3 ▶ $year += 2000 if $year < 100;
Branch: 1 branch
BranchTrueFalseTotal
if $year < 100 0 3 3
784 3 $year_specified = 1;
785  
786 ### format: printf "isodate %s -> Day %d, Month %s, Year %d\n", $piecesref->{isodate}, $day, $month, $year
787 }
788  
789 13 ▶ if ((defined $piecesref->{usdate}) && ($piecesref->{usdate})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $piecesref->{"usdate"} and $piecesref->{"usdate"}) 3 10 13
Condition66%2/3
defined $piecesref->{"usdate"} and $piecesref->{"usdate"}
!ll&&!rl&&r
1003
MC/DC50%1/2
defined $piecesref->{"usdate"} and $piecesref->{"usdate"}
defined $piecesref->{"usdate"} $piecesref->{"usdate"}
Truth table66%2/3
A and B
A= defined $piecesref->{"usdate"}B= $piecesref->{"usdate"}
ABresult
0X0
100
111
790 3 ($month, $day, $year) = ($piecesref->{usdate} =~ /(\w+)\W+(\d+)\W+(\d+)/);
791 3 ▶ $year += 2000 if $year < 100;
Branch: 1 branch
BranchTrueFalseTotal
if $year < 100 0 3 3
792 3 $year_specified = 1;
793  
794 ### format: printf STDERR "usdate %s -> Day %d, Month %s, Year %d\n", $piecesref->{usdate}, $day, $month, $year
795 }
796  
797 13 ▶ if ((defined $piecesref->{eurodate}) && ($piecesref->{eurodate})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $piecesref->{"eurodate"} and $piecesref->{"eurodate"}) 3 10 13
Condition66%2/3
defined $piecesref->{"eurodate"} and $piecesref->{"eurodate"}
!ll&&!rl&&r
1003
MC/DC50%1/2
defined $piecesref->{"eurodate"} and $piecesref->{"eurodate"}
defined $piecesref->{"eurodate"} $piecesref->{"eurodate"}
Truth table66%2/3
A and B
A= defined $piecesref->{"eurodate"}B= $piecesref->{"eurodate"}
ABresult
0X0
100
111
798 3 ($day, $month, $year) = ($piecesref->{eurodate} =~ /(\d+)\W+(\w+)\W+(\d+)/);
799 3 ▶ $year += 2000 if $year < 100;
Branch: 1 branch
BranchTrueFalseTotal
if $year < 100 0 3 3
800 3 $year_specified = 1;
801  
802 ### format: printf STDERR "eurodate %s -> Day %d, Month %s, Year %d\n", $piecesref->{eurodate}, $day, $month, $year
803 }
804  
805 13 ▶ if (defined ($piecesref->{year})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $piecesref->{"year"}) 1 12 13
806 1 $year = $piecesref->{year};
807 1 ▶ $year += 2000 if $year < 100;
Branch: 1 branch
BranchTrueFalseTotal
if $year < 100 1 0 1
808 1 $year_specified = 1;
809  
810 ### format: printf "year %s -> Year %d\n", $piecesref->{year}, $year
811 }
812  
813 13 ▶ if (defined ($piecesref->{month})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $piecesref->{"month"}) 3 10 13
814 3 $month = $piecesref->{month};
815  
816 ### format: printf "month %s -> Month %s\n", $piecesref->{month}, $month
817 }
818  
819 13 ▶ if (defined ($piecesref->{day})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $piecesref->{"day"}) 3 10 13
820 3 $day = $piecesref->{day};
821  
822 ### format: printf "day %s -> Day %d\n", $piecesref->{day}, $day
823 }
824  
825 13 ▶ $month = $mnames{lc(substr($month,0,3))} if ($month =~ /\D/);
Branch: 1 branch
BranchTrueFalseTotal
if $month =~ /\D/ 8 5 13
826 13 ▶ $year-- if (($year_specified == 0) && ($this_month < $month));
Branch: 1 branch
BranchTrueFalseTotal
if $year_specified == 0 and $this_month < $month 2 11 13
Condition100%3/3
$year_specified == 0 and $this_month < $month
!ll&&!rl&&r
1012
MC/DC100%2/2
$year_specified == 0 and $this_month < $month
$year_specified == 0 $this_month < $month
Truth table100%3/3
A and B
A= $year_specified == 0B= $this_month < $month
ABresult
0X0
100
111
827  
828 ### format: printf STDERR "Final Year-Month-Day -> %04d-%02d-%02d\n", $year, $month, $day
829  
830 13 $inforef->{$symbol, "date"} = sprintf "%02d/%02d/%04d", $month, $day, $year;
831 13 $inforef->{$symbol, "isodate"} = sprintf "%04d-%02d-%02d", $year, $month, $day;
832 }
833  
834 ################################################################################
835 #
836 # Public Class or Object Methods
837 #
838 ################################################################################
839  
840 # =======================================================================
841 # Helper function that can scale a field. This is useful because it
842 # handles things like ranges "105.4 - 108.3", and not just straight fields.
843 #
844 # The function takes a string or number to scale, and the factor to scale
845 # it by. For example, scale_field("1023","0.01") would return "10.23".
846  
847 1 ▶sub scale_field {
Subroutine scale_field: called CC=4 SCAR=14.0
Pod documented
848 1 ▶ shift if ref $_[0]; # Shift off the object, if there is one.
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] 0 1 1
849  
850 1 my ($field, $scale) = @_;
851 1 my @chunks = split(/([^0-9.])/,$field);
852  
853 1 ▶ for (my $i=0; $i < @chunks; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @chunks) 1 1 2
854 1 ▶ next unless $chunks[$i] =~ /\d/;
Branch: 1 branch
BranchTrueFalseTotal
unless $chunks[$i] =~ /\d/ 0 1 1
855 1 $chunks[$i] *= $scale;
856 }
857 1 return join("",@chunks);
858 }
859  
860 # =======================================================================
861 # currency (public object method)
862 #
863 # currency allows the conversion of one currency to another.
864 #
865 # Usage: $quoter->currency("USD","AUD");
866 # $quoter->currency("15.95 USD","AUD");
867 #
868 # undef is returned upon error.
869  
870 0 ▶sub currency {
Subroutine currency: not called CC=12 SCAR=50.5
Pod documented
871 0 ▶ my $this = ref($_[0]) ? shift : _dummy();
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 0 0
872  
873 0 my ($from_code, $to_code) = @_;
874 0 ▶ return unless ($from_code and $to_code);
Branch: 1 branch
BranchTrueFalseTotal
unless $from_code and $to_code 0 0 0
Condition0%0/3
$from_code and $to_code
!ll&&!rl&&r
000
MC/DC0%0/2
$from_code and $to_code
$from_code $to_code
Truth table0%0/3
A and B
A= $from_codeB= $to_code
ABresult
0X0
100
111
875  
876 0 $from_code =~ s/^\s*(\d*\.?\d*)\s*//;
877 0 ▶ my $amount = $1 || 1;
Condition0%0/2
$1 || 1
l!l
00
MC/DC0%0/1
$1 || 1
$1
Truth table0%0/2
A
A= $1
Aresult
11
00
878  
879 0 $to_code = uc($to_code);
880 0 $from_code = uc($from_code);
881  
882 0 ▶ return $amount if ($from_code eq $to_code); # Trivial case.
Branch: 1 branch
BranchTrueFalseTotal
if $from_code eq $to_code 0 0 0
883  
884 0 my $ua = $this->get_user_agent;
885  
886 0 foreach my $rate (@{$this->{currency_rate_method}}) {
887 ### rate: ref($rate)
888 0 my $final = eval {
889 0 my ($from, $to) = $rate->multipliers($ua, $from_code, $to_code);
890  
891 0 ▶ die("Failed to find currency rates for $from_code or $to_code") unless defined $from and defined $to;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $from and defined $to 0 0 0
Condition0%0/3
defined $from and defined $to
!ll&&!rl&&r
000
MC/DC0%0/2
defined $from and defined $to
defined $from defined $to
Truth table0%0/3
A and B
A= defined $fromB= defined $to
ABresult
0X0
100
111
892  
893 ### to weight : $to
894 ### from weight: $from
895 ### amount : $amount
896  
897 # Is from closest to (amount, to, amount * to)?
898 # (amount * to) / from
899 0 my $delta = abs($amount - $from);
900 0 my $result = ($amount/$from) * $to;
901 ### amount/from -> delta/result : ($delta, $result)
902 0 ▶ if ($delta > abs($to - $from)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($delta > abs $to - $from) 0 0 0
903 0 $delta = abs($to - $from);
904 0 $result = ($to/$from) * $amount;
905 ### to/from -> delta/result : ($delta, $result)
906 }
907 0 ▶ if ($delta > abs($amount*$to - $from)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($delta > abs $amount * $to - $from) 0 0 0
908 0 $delta = abs($amount*$to - $from);
909 0 $result = ($amount * $to)/$from;
910 ### (amount * to)/from -> delta/result : ($delta, $result)
911 }
912  
913 0 return $result;
914 };
915  
916 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
917 ### Rate Error: chomp($@), $@
918 0 next;
919 }
920  
921 0 return $final;
922 }
923  
924 0 return;
925 }
926  
927 # =======================================================================
928 # currency_lookup (public object method)
929 #
930 # search for available currency codes
931 #
932 # Usage:
933 # $currency = $quoter->currency_lookup();
934 # $currency = $quoter->currency_lookup( name => "Dollar");
935 # $currency = $quoter->currency_loopup( country => qw/denmark/i );
936 # $currency = $q->currency_lookup(country => qr/united states/i, number => 840);
937 #
938 # If more than one lookup parameter is given all must match for
939 # a currency to match.
940 #
941 # undef is returned upon error.
942  
943 6 ▶sub currency_lookup {
Subroutine currency_lookup: called CC=5 SCAR=16.1
Pod documented
944 6 ▶ my $this = ref $_[0] ? shift : _dummy();
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 6 6
945  
946 6 my %params = @_;
947 6 my $currencies = Finance::Quote::Currencies::known_currencies();
948  
949 6 my %attributes = map {$_ => 1} map {keys %$_} values %$currencies;
950  
951 6 for my $key (keys %params ) {
952 7 ▶ if ( ! exists $attributes{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $attributes{$key}) 1 6 7
953 1 warn "Invalid parameter: $key";
954 1 return;
955 }
956 }
957
958 5 ▶ while (my ($tag, $check) = each(%params)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %params) 6 5 11
959 6 $currencies = {map {$_ => $currencies->{$_}} grep {_smart_compare($currencies->{$_}->{$tag}, $check)} keys %$currencies};
960 }
961
962 5 return $currencies;
963 }
964  
965 # =======================================================================
966 # parse_csv (public object method)
967 #
968 # Grabbed from the Perl Cookbook. Parsing csv isn't as simple as you thought!
969 #
970 sub parse_csv
971 0 ▶{
Subroutine parse_csv: not called CC=4 SCAR=30.0
Pod documented
972 0 ▶ shift if (ref $_[0]); # Shift off the object if we have one.
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] 0 0 0
973 0 my $text = shift; # record containing comma-separated values
974 0 my @new = ();
975  
976 0 ▶ push(@new, $+) while $text =~ m{
Branch: 1 branch
BranchTrueFalseTotal
$text =~ / # the first part groups the phrase inside the quotes. # see explanation of this pattern in MRE "([^\"\\]*(?:\\.[^\"\\]*)*)",? | ([^,]+),? | , /gx and do { push @new, $+ } 0 0 0
977 # the first part groups the phrase inside the quotes.
978 # see explanation of this pattern in MRE
979 "([^\"\\]*(?:\\.[^\"\\]*)*)",?
980 | ([^,]+),?
981 | ,
982 }gx;
983 0 ▶ push(@new, undef) if substr($text, -1,1) eq ',';
Branch: 1 branch
BranchTrueFalseTotal
if substr($text, -1, 1) eq "," 0 0 0
984  
985 0 return @new; # list of values that were comma-separated
986 }
987  
988 # =======================================================================
989 # parse_csv_semicolon (public object method)
990 #
991 # Grabbed from the Perl Cookbook. Parsing csv isn't as simple as you thought!
992 #
993 sub parse_csv_semicolon
994 0 ▶{
Subroutine parse_csv_semicolon: not called CC=4 SCAR=30.0
Pod documented
995 0 ▶ shift if (ref $_[0]); # Shift off the object if we have one.
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] 0 0 0
996 0 my $text = shift; # record containing comma-separated values
997 0 my @new = ();
998  
999 0 ▶ push(@new, $+) while $text =~ m{
Branch: 1 branch
BranchTrueFalseTotal
$text =~ / # the first part groups the phrase inside the quotes. # see explanation of this pattern in MRE "([^\"\\]*(?:\\.[^\"\\]*)*)";? | ([^;]+);? | ; /gx and do { push @new, $+ } 0 0 0
1000 # the first part groups the phrase inside the quotes.
1001 # see explanation of this pattern in MRE
1002 "([^\"\\]*(?:\\.[^\"\\]*)*)";?
1003 | ([^;]+);?
1004 | ;
1005 }gx;
1006 0 ▶ push(@new, undef) if substr($text, -1,1) eq ';';
Branch: 1 branch
BranchTrueFalseTotal
if substr($text, -1, 1) eq ";" 0 0 0
1007  
1008 0 return @new; # list of values that were comma-separated
1009 }
1010  
1011 ###############################################################################
1012 #
1013 # Legacy Class Methods
1014 #
1015 ###############################################################################
1016  
1017 0 ▶sub sources {
Subroutine sources: not called CC=1 SCAR=6.9
Pod documented
1018 0 return get_methods();
1019 }
1020  
1021 215 ▶sub default_currency_fields {
Subroutine default_currency_fields: called CC=1 SCAR=0.0
Pod documented
1022 215 return get_default_currency_fields();
1023 }
1024  
1025 ###############################################################################
1026 #
1027 # Legacy Class or Object Methods
1028 #
1029 ###############################################################################
1030  
1031 # =======================================================================
1032 # set_currency (public object method)
1033 #
1034 # set_currency allows information to be requested in the specified
1035 # currency. If called with no arguments then information is returned
1036 # in the default currency.
1037 #
1038 # Requesting stocks in a particular currency increases the time taken,
1039 # and the likelyhood of failure, as additional operations are required
1040 # to fetch the currency conversion information.
1041 #
1042 # This method should only be called from the quote object unless you
1043 # know what you are doing.
1044  
1045 0 ▶sub set_currency {
Subroutine set_currency: not called CC=4 SCAR=30.0
Pod documented
1046 0 ▶ if (@_ == 1 or !ref($_[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 or not ref $_[0]) 0 0 0
Condition0%0/3
@_ == 1 or not ref $_[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
@_ == 1 or not ref $_[0]
@_ == 1 not ref $_[0]
Truth table0%0/3
A or not(B)
A= @_ == 1B= not ref $_[0]
ABresult
1X1
011
000
1047 # Direct or class call - there is no class default currency
1048 0 return;
1049 }
1050  
1051 0 my $this = shift;
1052 0 ▶ if (defined($_[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[0]) 0 0 0
1053 0 $this->set_fetch_currency($_[0]);
1054 }
1055  
1056 0 return $this->get_fetch_currency();
1057 }
1058  
1059 # =======================================================================
1060 # Timeout code. If called on a particular object, then it sets
1061 # the timout for that object only. If called as a class method
1062 # (or as Finance::Quote::timeout) then it sets the default timeout
1063 # for all new objects that will be created.
1064  
1065 0 ▶sub timeout {
Subroutine timeout: not called CC=3 SCAR=24.8
Pod documented
1066 0 ▶ if (@_ == 1 or !ref($_[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 or not ref $_[0]) 0 0 0
Condition0%0/3
@_ == 1 or not ref $_[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
@_ == 1 or not ref $_[0]
@_ == 1 not ref $_[0]
Truth table0%0/3
A or not(B)
A= @_ == 1B= not ref $_[0]
ABresult
1X1
011
000
1067 # Direct or class call
1068 0 Finance::Quote::set_default_timeout(shift);
1069 0 return Finance::Quote::get_default_timeout();
1070 }
1071  
1072 # Otherwise we were called through an object. Yay.
1073 # Set the timeout in this object only.
1074 0 my $this = shift;
1075 0 $this->set_timeout(shift);
1076 0 return $this->get_timeout();
1077 }
1078  
1079 ###############################################################################
1080 #
1081 # Legacy Object Methods
1082 #
1083 ###############################################################################
1084  
1085 # =======================================================================
1086 # failover (public object method)
1087 #
1088 # This sets/gets whether or not it's acceptable to use failover techniques.
1089  
1090 0 ▶sub failover {
Subroutine failover: not called CC=2 SCAR=17.9
Pod documented
1091 0 my $this = shift;
1092 0 my $value = shift;
1093  
1094 0 ▶ $this->set_failover($value) if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 0 0 0
1095 0 return $this->get_failover();
1096 }
1097  
1098 # =======================================================================
1099 # require_labels (public object method)
1100 #
1101 # Require_labels indicates which labels are required for lookups. Only methods
1102 # that have registered all the labels specified in the list passed to
1103 # require_labels() will be called.
1104 #
1105 # require_labels takes a list of required labels. When called with no
1106 # arguments, the require list is cleared.
1107 #
1108 # This method always succeeds.
1109  
1110 0 ▶sub require_labels {
Subroutine require_labels: not called CC=1 SCAR=6.9
Pod documented
1111 0 my $this = shift;
1112 0 my @labels = @_;
1113 0 $this->set_required_labels(\@labels);
1114 0 return;
1115 }
1116  
1117 # =======================================================================
1118 # user_agent (public object method)
1119 #
1120 # Returns a LWP::UserAgent which conforms to the relevant timeouts,
1121 # proxies, and other settings on the particular Finance::Quote object.
1122 #
1123 # This function is mainly intended to be used by the modules that we load,
1124 # but it can be used by the application to directly play with the
1125 # user-agent settings.
1126  
1127 0 ▶sub user_agent {
Subroutine user_agent: not called CC=1 SCAR=6.9
Pod documented
1128 0 my $this = shift;
1129 0 return $this->get_user_agent();
1130 }
1131  
1132 52 1;
1133  
1134 __END__
« Quote/ASX.pm ↑ Summary Quote/TMX.pm »