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