Debian Codegraph @

lib/Finance/Quote.pm

raw
1 #!/usr/bin/perl -w
2 #
3 # vi: set ts=2 sw=2 noai ic showmode showmatch:
4 #
5 # Copyright (C) 1998, Dj Padzensky <[email protected]>
6 # Copyright (C) 1998, 1999 Linas Vepstas <[email protected]>
7 # Copyright (C) 2000, Yannick LE NY <[email protected]>
8 # Copyright (C) 2000, Paul Fenwick <[email protected]>
9 # Copyright (C) 2000, Brent Neal <[email protected]>
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 use strict;
35
36 use constant DEBUG => $ENV{DEBUG};
37 use if DEBUG, 'Smart::Comments', '###';
38
39 use Module::Load;
40 use Exporter ();
41 use Carp;
42 use Finance::Quote::UserAgent;
43 use HTTP::Request::Common;
44 use Encode;
45 use JSON qw( decode_json );
46
47 use vars qw/@ISA @EXPORT @EXPORT_OK @EXPORT_TAGS
48 $TIMEOUT @MODULES %MODULES %METHODS $AUTOLOAD
49 @CURRENCY_RATES_MODULES $USE_EXPERIMENTAL_UA/;
50
51 our $VERSION = '1.71'; # VERSION
52
53 @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 @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 NSEIndia
91 NZX
92 OnVista
93 SIX
94 Sinvestor
95 StockData
96 Stooq
97 SwissFundData
98 TesouroDireto
99 TMX
100 Tradegate
101 TreasuryDirect
102 TSP
103 TwelveData
104 Union
105 USBonds
106 XETRA
107 YahooJSON
108 YahooWeb
109 ZA
110 /;
111
112 @ISA = qw/Exporter/;
113 @EXPORT = ();
114 @EXPORT_OK = qw/asx currency_lookup/;
115 @EXPORT_TAGS = ( all => [@EXPORT_OK]);
116
117 $USE_EXPERIMENTAL_UA = 0;
118
119 ################################################################################
120 #
121 # Private Class Methods
122 #
123 ################################################################################
124 # Autoload method for obsolete methods. This also allows people to
125 # call methods that objects export without having to go through fetch.
126
127 sub AUTOLOAD {
128 my $method = $AUTOLOAD;
129 (my $name = $method) =~ s/.*:://;
130
131 # Force the dummy object (and hence default methods) to be loaded.
132 _dummy();
133
134 if (exists($METHODS{$name})) {
135 no strict 'refs'; ## no critic
136
137 *$method = sub {
138 my $this = ref($_[0]) ? shift : _dummy();
139 $this->fetch($name, @_);
140 };
141
142 return &$method;
143 }
144
145 carp "$AUTOLOAD does not refer to a known method.";
146 }
147
148 # Dummy destroy function to avoid AUTOLOAD catching it.
149 sub DESTROY { return; }
150
151 # _convert (private object method)
152 #
153 # This function converts between one currency and another. It expects
154 # to receive a hashref to the information, a reference to a list
155 # of the stocks to be converted, and a reference to a list of fields
156 # that conversion should apply to.
157
158 {
159 my %conversion; # Conversion lookup table.
160
161 sub _convert {
162 my $this = shift;
163 my $info = shift;
164 my $stocks = shift;
165 my $convert_fields = shift;
166 my $new_currency = $this->{"currency"};
167
168 # Skip all this unless they actually want conversion.
169 return unless $new_currency;
170
171 foreach my $stock (@$stocks) {
172 my $currency;
173
174 # Skip stocks that don't have a currency.
175 next unless ($currency = $info->{$stock,"currency"});
176
177 # Skip if it's already in the same currency.
178 next if ($currency eq $new_currency);
179
180 # Lookup the currency conversion if we haven't
181 # already.
182 unless (exists $conversion{$currency,$new_currency}) {
183 $conversion{$currency,$new_currency} =
184 $this->currency($currency,$new_currency);
185 }
186
187 # Make sure we have a reasonable currency conversion.
188 # If we don't, mark the stock as bad.
189 unless ($conversion{$currency,$new_currency}) {
190 $info->{$stock,"success"} = 0;
191 $info->{$stock,"errormsg"} =
192 "Currency conversion failed.";
193 next;
194 }
195
196 # Okay, we have clean data. Convert it. Ideally
197 # we'd like to just *= entire fields, but
198 # unfortunately some things (like ranges,
199 # capitalisation, etc) don't take well to that.
200 # Hence we pull out any numbers we see, convert
201 # them, and stick them back in. That's pretty
202 # yucky, but it works.
203
204 foreach my $field (@$convert_fields) {
205 next unless (defined $info->{$stock,$field});
206
207 $info->{$stock,$field} = $this->scale_field($info->{$stock,$field},$conversion{$currency,$new_currency});
208 }
209
210 # Set the new currency.
211 $info->{$stock,"currency"} = $new_currency;
212 }
213 }
214 }
215
216 # =======================================================================
217 # _dummy (private function)
218 #
219 # _dummy returns a Finance::Quote object. I'd really rather not have
220 # this, but to maintain backwards compatibility we hold on to it.
221 {
222 my $dummy_obj;
223 sub _dummy {
224 return $dummy_obj ||= Finance::Quote->new;
225 }
226 }
227
228 # _load_module (private class method)
229 # _load_module loads a module(s) and registers its various methods for
230 # use.
231
232 sub _load_modules {
233 my $class = shift;
234 my $baseclass = ref $class || $class;
235
236 my @modules = @_;
237
238 # Go to each module and use them. Also record what methods
239 # they support and enter them into the %METHODS hash.
240
241 foreach my $module (@modules) {
242 my $modpath = "${baseclass}::${module}";
243 unless (defined($MODULES{$modpath})) {
244
245 eval {
246 load $modpath;
247 $MODULES{$modpath} = 1;
248
249 my %methodhash = $modpath->methods;
250 my %labelhash = $modpath->labels;
251 my $curr_fields_func = $modpath->can("currency_fields") || \&default_currency_fields;
252 my @currency_fields = &$curr_fields_func;
253 my %seen;
254 @currency_fields = grep {!$seen{$_}++} @currency_fields;
255
256 foreach my $method (keys %methodhash) {
257 push (@{$METHODS{$method}},
258 { name => $module,
259 modpath => $modpath,
260 function => $methodhash{$method},
261 labels => $labelhash{$method},
262 currency_fields => \@currency_fields});
263 }
264 };
265 carp $@ if $@;
266 }
267 }
268 }
269
270 # _smart_compare (private method function)
271 #
272 # This function compares values where the method depends on the
273 # type of the parameters.
274 # val1, val2
275 # scalar,scaler - test for substring match
276 # scalar,regex - test val1 against val2 regex
277 # array,scalar - return true if any element of array substring matches scalar
278 # array,regex - return true if any element of array matches regex
279 sub _smart_compare {
280 my ($val1, $val2) = @_;
281
282 if ( ref $val1 eq 'ARRAY' ) {
283 if ( ref $val2 eq 'Regexp' ) {
284 my @r = grep {$_ =~ $val2} @$val1;
285 return @r > 0;
286 }
287 else {
288 my @r = grep {$_ =~ /$val2/} @$val1;
289 return @r > 0;
290 }
291 }
292 else {
293 if ( ref $val2 eq 'Regexp' ) {
294 return $val1 =~ $val2;
295 }
296 else {
297 return index($val1, $val2) > -1
298 }
299 }
300 }
301
302 # This is a list of fields that will be automatically converted during
303 # currency conversion. If a module provides a currency_fields()
304 # function then that list will be used instead.
305
306 sub get_default_currency_fields {
307 return qw/last high low net bid ask close open day_range year_range
308 eps div cap nav price/;
309 }
310
311 sub get_default_timeout {
312 return $TIMEOUT;
313 }
314
315 # get_methods returns a list of sources which can be passed to fetch to
316 # obtain information.
317
318 sub get_methods {
319 # Create a dummy object to ensure METHODS is populated
320 my $t = Finance::Quote->new();
321 return(wantarray ? keys %METHODS : [keys %METHODS]);
322 }
323
324 # return hash:
325 #
326 # quote_methods => hash of
327 # method_name => array of module names
328 # quote_modules => hash of
329 # module_name => array of parameters
330 # currency_modules => hash of
331 # module_name => array of parameters
332 #
333 # {
334 # 'quote_methods' => {'group' => ['module', 'module'], ...},
335 # 'quote_modules' => {'abc' => ['API_KEY'], ...},
336 # 'currency_modules' => {'xyz' => [], 'lmn' => ['USER_NAME', 'API_KEY']},
337 # }
338
339 sub get_features {
340 # Create a dummy object to ensure METHODS is populated
341 my $t = Finance::Quote->new(currency_rates => {order => \@CURRENCY_RATES_MODULES});
342 my $baseclass = ref $t;
343
344 my %feature = (
345 'quote_methods' => {map {$_, [map {$_->{name}} @{$METHODS{$_}}]} keys %METHODS},
346 'quote_modules' => {map {$_, []} @MODULES},
347 'currency_modules' => {map {$_, []} @CURRENCY_RATES_MODULES},
348 );
349
350 my %mods = ('quote_modules' => $baseclass,
351 'currency_modules' => "${baseclass}::CurrencyRates");
352
353 while (my ($field, $base) = each %mods) {
354 foreach my $name (keys %{$feature{$field}}) {
355 my $modpath = "${base}::${name}";
356
357 if ($modpath->can("parameters")) {
358 push (@{$feature{$field}->{$name}}, $modpath->parameters());
359 }
360 }
361 }
362
363 return %feature;
364 }
365
366 # =======================================================================
367 # new (public class method)
368 #
369 # Returns a new Finance::Quote object.
370 #
371 # Arguments ::
372 # - zero or more module names from the Finance::Quote::get_sources list
373 # - zero or more named parameters, passes as name => value
374 #
375 # Named Parameters ::
376 # - timeout # timeout in seconds for web requests
377 # - failover # boolean value indicating if failover is acceptable
378 # - fetch_currency # currency code for fetch results
379 # - required_labels # array of required labels in fetch results
380 # - <module-name> # hash specific to various Finance::Quote modules
381 #
382 # new() # default constructor
383 # new('a', 'b') # load only modules a and b
384 # new(timeout => 30) # load all default modules, set timeout
385 # new('a', fetch_currency => 'X') # load only module a, use currency X for results
386 # new('z' => {API_KEY => 'K'}) # load all modules, pass hash to module z constructor
387 # new('z', 'z' => {API_KEY => 'K'}) # load only module z and pass hash to its constructor
388 #
389 # Enivornment Variables ::
390 # - FQ_LOAD_QUOTELET # if no modules named in argument list, use ones in this variable
391 #
392 # Return Value ::
393 # - Finanace::Quote object
394
395 sub new {
396 # Create and bless object
397 my $self = shift;
398 my $class = ref($self) || $self;
399
400 my $this = {};
401 bless $this, $class;
402
403 # To add a named parameter:
404 # 0. Document it in the POD for new
405 # 1. Add a default value for $this->{object-name}
406 # 2. Add the 'user-visible-name' => [type, object-name] to %named_parameter
407
408 # Check for FQ_CURRENCY - preferred currency module
409 # Set to AlphaVantage if not set or not in @CURRENCY_RATES_MODULES
410 my $CURRENCY_MODULE;
411 if (!$ENV{FQ_CURRENCY}) {
412 $CURRENCY_MODULE='AlphaVantage';
413 } else {
414 if ( grep( /^$ENV{FQ_CURRENCY}$/, @CURRENCY_RATES_MODULES ) ) {
415 $CURRENCY_MODULE=$ENV{FQ_CURRENCY}
416 } else {
417 $CURRENCY_MODULE='AlphaVantage';
418 }
419 }
420
421 # Default values
422 $this->{FAILOVER} = 1;
423 $this->{REQUIRED} = [];
424 $this->{TIMEOUT} = $TIMEOUT if defined($TIMEOUT);
425 $this->{currency_rates} = {order => [$CURRENCY_MODULE]};
426
427 # Sort out arguments
428 my %named_parameter = (timeout => ['', 'TIMEOUT'],
429 failover => ['', 'FAILOVER'],
430 fetch_currency => ['', 'currency'],
431 required_labels => ['ARRAY', 'REQUIRED'],
432 currency_rates => ['HASH', 'currency_rates']);
433
434 $this->{module_specific_data} = {};
435 my @load_modules = ();
436
437 for (my $i = 0; $i < @_; $i++) {
438 if (exists $named_parameter{$_[$i]}) {
439 die "missing value for named parameter $_[$i]" if $i + 1 == @_;
440 die "unexpect type for value of named parameter $_[$i]" if ref $_[$i+1] ne $named_parameter{$_[$i]}[0];
441
442 $this->{$named_parameter{$_[$i]}[1]} = $_[$i+1];
443 $i += 1;
444 }
445 elsif ($i + 1 < @_ and ref $_[$i+1] eq 'HASH') {
446 $this->{module_specific_data}->{$_[$i]} = $_[$i+1];
447 $i += 1;
448 }
449 elsif ($_[$i] eq '-defaults') {
450 push (@load_modules, @MODULES);
451 }
452 else {
453 push (@load_modules, $_[$i]);
454 }
455 }
456
457 # Honor FQ_LOAD_QUOTELET if @load_modules is empty
458 if ($ENV{FQ_LOAD_QUOTELET} and !@load_modules) {
459 @load_modules = split(' ',$ENV{FQ_LOAD_QUOTELET});
460 if ($load_modules[0] eq '-defaults') {
461 shift @load_modules;
462 push(@load_modules, @MODULES);
463 }
464 }
465 elsif (@load_modules == 0) {
466 push(@load_modules, @MODULES);
467 }
468
469 $this->_load_modules(@load_modules);
470
471 # Load the currency rate methods
472 my %currency_check = map { $_ => 1 } @CURRENCY_RATES_MODULES;
473 $this->{currency_rate_method} = [];
474 foreach my $method (@{$this->{currency_rates}->{order}}) {
475 unless (defined($currency_check{$method})) {
476 carp "Unknown curreny rates method: $method";
477 return;
478 }
479
480 my $method_path = "${class}::CurrencyRates::${method}";
481 eval {
482 autoload $method_path;
483 my $args = exists $this->{currency_rates}->{lc($method)} ? $this->{currency_rates}->{lc($method)} : {};
484 my $rate = $method_path->new($args);
485 die unless defined $rate;
486
487 push(@{$this->{currency_rate_method}}, $rate);
488 };
489
490 if ($@) {
491 next;
492 }
493 }
494
495 return $this;
496 }
497
498 sub set_default_timeout {
499 $TIMEOUT = shift;
500 }
501
502 ################################################################################
503 #
504 # Private Object Methods
505 #
506 ################################################################################
507
508 # _require_test (private object method)
509 #
510 # This function takes an array. It returns true if all required
511 # labels appear in the arrayref. It returns false otherwise.
512 #
513 # This function could probably be made more efficient.
514
515 sub _require_test {
516 my $this = shift;
517 my %available;
518 @available{@_} = (); # Ooooh, hash-slice. :)
519 my @required = @{$this->{REQUIRED}};
520 return 1 unless @required;
521 for (my $i = 0; $i < @required; $i++) {
522 return 0 unless exists $available{$required[$i]};
523 }
524 return 1;
525 }
526
527 ################################################################################
528 #
529 # Public Object Methods
530 #
531 ################################################################################
532
533 # If $str ends with a B like "20B" or "1.6B" then expand it as billions like
534 # "20000000000" or "1600000000".
535 #
536 # This is done with string manipulations so floating-point rounding doesn't
537 # produce spurious digits for values like "1.6" which aren't exactly
538 # representable in binary.
539 #
540 # Is "B" for billions the only abbreviation from Yahoo?
541 # Could extend and rename this if there's also millions or thousands.
542 #
543 # For reference, if the value was just for use within perl then simply
544 # substituting to exponential "1.5e9" might work. But expanding to full
545 # digits seems a better idea as the value is likely to be printed directly
546 # as a string.
547 sub B_to_billions {
548 my ($self,$str) = @_;
549
550 # B_to_billions() $str
551 if ($str =~ s/B$//i) {
552 $str = $self->decimal_shiftup ($str, 9);
553 }
554 return $str;
555 }
556
557 # $str is a number like "123" or "123.45"
558 # return it with the decimal point moved $shift places to the right
559 # must have $shift>=1
560 # eg. decimal_shiftup("123",3) -> "123000"
561 # decimal_shiftup("123.45",1) -> "1234.5"
562 # decimal_shiftup("0.25",1) -> "2.5"
563 #
564 sub decimal_shiftup {
565 my ($self, $str, $shift) = @_;
566
567 # delete decimal point and set $after to count of chars after decimal.
568 # Leading "0" as in "0.25" is deleted too giving "25" so as not to end up
569 # with something that might look like leading 0 for octal.
570 my $after = ($str =~ s/(?:^0)?\.(.*)/$1/ ? length($1) : 0);
571
572 $shift -= $after;
573 # now $str is an integer and $shift is relative to the end of $str
574
575 if ($shift >= 0) {
576 # moving right, eg. "1234" becomes "12334000"
577 return $str . ('0' x $shift); # extra zeros appended
578 } else {
579 # negative means left, eg. "12345" becomes "12.345"
580 # no need to prepend zeros since demanding initial $shift>=1
581 substr ($str, $shift,0, '.'); # new '.' at shifted spot from end
582 return $str;
583 }
584 }
585
586 # =======================================================================
587 # fetch (public object method)
588 #
589 # Fetch is a wonderful generic fetcher. It takes a method and stuff to
590 # fetch. It's a nicer interface for when you have a list of stocks with
591 # different sources which you wish to deal with.
592 sub fetch {
593 my $this = ref($_[0]) ? shift : _dummy();
594
595 my $method = lc(shift);
596 my @stocks = @_;
597
598 unless (exists $METHODS{$method}) {
599 carp "Undefined fetch-method $method passed to ".
600 "Finance::Quote::fetch";
601 return;
602 }
603
604 {
605 # Setting no critic to avoid Stricture disabled failure
606 # in t/04-critic.t
607 ## no critic
608 no strict 'vars';
609 our $VERSION = '0.00' unless defined $VERSION;
610 ## use critic
611 unless ($ENV{"FQ_NOCOUNT"}) {
612 # Temporary Counting - not concerned about return code
613 my $COUNT_URL =
614 'http://www.panix.com/~hd-fxsts/finance-quote.html?fqversion=' . $VERSION . '&fqmethod=' . $method;
615 my $count_ua = LWP::UserAgent->new(timeout => 10);
616 my $count_response = $count_ua->head($COUNT_URL);
617
618 ### COUNT_URL: $COUNT_URL
619 ### Code: $count_response->code
620 }
621 }
622
623 # Failover code. This steps through all available methods while
624 # we still have failed stocks to look-up. This loop only
625 # runs a single time unless FAILOVER is defined.
626 my %returnhash = ();
627
628 foreach my $methodinfo (@{$METHODS{$method}}) {
629 my $funcref = $methodinfo->{"function"};
630 next unless $this->_require_test(@{$methodinfo->{"labels"}});
631 my @failed_stocks = ();
632 %returnhash = (%returnhash,&$funcref($this,@stocks));
633
634 foreach my $stock (@stocks) {
635 push(@failed_stocks,$stock)
636 unless ($returnhash{$stock,"success"});
637 }
638
639 $this->_convert(\%returnhash,\@stocks,
640 $methodinfo->{"currency_fields"});
641
642 last unless $this->{FAILOVER};
643 last unless @failed_stocks;
644 @stocks = @failed_stocks;
645 }
646
647 return wantarray() ? %returnhash : \%returnhash;
648 }
649
650 sub get_failover {
651 my $self = shift;
652 return $self->{FAILOVER};
653 }
654
655 sub get_fetch_currency {
656 my $self = shift;
657 return $self->{currency};
658 }
659
660 sub get_required_labels {
661 my $self = shift;
662 return $self->{REQUIRED};
663 }
664
665 sub get_timeout {
666 my $self = shift;
667 return $self->{TIMEOUT};
668 }
669
670 sub get_user_agent {
671 my $this = shift;
672
673 return $this->{UserAgent} if $this->{UserAgent};
674
675 my $ua;
676
677 if ($USE_EXPERIMENTAL_UA) {
678 $ua = Finance::Quote::UserAgent->new;
679 } else {
680 $ua = LWP::UserAgent->new;
681 }
682
683 $ua->timeout($this->{TIMEOUT}) if defined($this->{TIMEOUT});
684 $ua->env_proxy;
685
686 $this->{UserAgent} = $ua;
687
688 return $ua;
689 }
690
691 sub isoTime {
692 my ($self,$timeString) = @_ ;
693 $timeString =~ tr/ //d ;
694 $timeString = uc $timeString ;
695 my $retTime = "00:00"; # return zero time if unparsable input
696 if ($timeString=~m/^(\d+)[\.:UH](\d+) *(AM|am|PM|pm)?/) {
697 my ($hours,$mins)= ($1-0,$2-0) ;
698 $hours-=12 if ($hours==12 && $3 && ($3 =~ /AM/i));
699 $hours+=12 if ($3 && ($3 =~ /PM/i) && ($hours != 12));
700 if ($hours>=0 && $hours<=23 && $mins>=0 && $mins<=59 ) {
701 $retTime = sprintf ("%02d:%02d", $hours, $mins) ;
702 }
703 }
704 return $retTime;
705 }
706
707 sub set_failover {
708 my $self = shift;
709 $self->{FAILOVER} = shift;
710 }
711
712 sub set_fetch_currency {
713 my $self = shift;
714 $self->{currency} = shift;
715 }
716
717 sub set_required_labels {
718 my $self = shift;
719 $self->{REQUIRED} = shift;
720 }
721
722 sub set_timeout {
723 my $self = shift;
724 $self->{TIMEOUT} = shift;
725 }
726
727 # =======================================================================
728 # store_date (public object method)
729 #
730 # Given the various pieces of a date, this functions figure out how to
731 # store them in both the pre-existing US date format (mm/dd/yyyy), and
732 # also in the ISO date format (yyyy-mm-dd). This function expects to
733 # be called with the arguments:
734 #
735 # (inforef, symbol_name, data_hash)
736 #
737 # The components of date hash can be any of:
738 #
739 # usdate - A date in mm/dd/yy or mm/dd/yyyy
740 # eurodate - A date in dd/mm/yy or dd/mm/yyyy
741 # isodate - A date in yy-mm-dd or yyyy-mm-dd, yyyy/mm/dd, yyyy.mm.dd, or yyyymmdd
742 # year - The year in yyyy
743 # month - The month in mm or mmm format (i.e. 07 or Jul)
744 # day - The day
745 # today - A flag to indicate todays date should be used.
746 #
747 # The separator for the *date forms is ignored. It can be any
748 # non-alphanumeric character. Any combination of year, month, and day
749 # values can be provided. Missing fields are filled in based upon
750 # today's date.
751 #
752 sub store_date
753 {
754 my $this = shift;
755 my $inforef = shift;
756 my $symbol = shift;
757 my $piecesref = shift;
758
759 my ($year, $month, $day, $this_month, $year_specified);
760 my %mnames = (jan => 1, feb => 2, mar => 3, apr => 4, may => 5, jun => 6,
761 jul => 7, aug => 8, sep => 9, oct =>10, nov =>11, dec =>12);
762
763 ### store_date symbol: $symbol
764 ### store_date pieces: $piecesref
765
766 # Default to today's date.
767 ($month, $day, $year) = (localtime())[4,3,5];
768 $month++;
769 $year += 1900;
770 $this_month = $month;
771 $year_specified = 0;
772
773 # Process the inputs
774 if ((defined $piecesref->{isodate}) && ($piecesref->{isodate})) {
775 if ($piecesref->{isodate} =~ /^([0-9]{4})([0-9]{2})([0-9]{2})$/) {
776 ($year, $month, $day) = ($1, $2, $3);
777 }
778 else {
779 ($year, $month, $day) = ($piecesref->{isodate} =~ m|([0-9]{4})\W+(\w+)\W+(\w+)|);
780 }
781
782 $year += 2000 if $year < 100;
783 $year_specified = 1;
784
785 ### format: printf "isodate %s -> Day %d, Month %s, Year %d\n", $piecesref->{isodate}, $day, $month, $year
786 }
787
788 if ((defined $piecesref->{usdate}) && ($piecesref->{usdate})) {
789 ($month, $day, $year) = ($piecesref->{usdate} =~ /(\w+)\W+(\d+)\W+(\d+)/);
790 $year += 2000 if $year < 100;
791 $year_specified = 1;
792
793 ### format: printf STDERR "usdate %s -> Day %d, Month %s, Year %d\n", $piecesref->{usdate}, $day, $month, $year
794 }
795
796 if ((defined $piecesref->{eurodate}) && ($piecesref->{eurodate})) {
797 ($day, $month, $year) = ($piecesref->{eurodate} =~ /(\d+)\W+(\w+)\W+(\d+)/);
798 $year += 2000 if $year < 100;
799 $year_specified = 1;
800
801 ### format: printf STDERR "eurodate %s -> Day %d, Month %s, Year %d\n", $piecesref->{eurodate}, $day, $month, $year
802 }
803
804 if (defined ($piecesref->{year})) {
805 $year = $piecesref->{year};
806 $year += 2000 if $year < 100;
807 $year_specified = 1;
808
809 ### format: printf "year %s -> Year %d\n", $piecesref->{year}, $year
810 }
811
812 if (defined ($piecesref->{month})) {
813 $month = $piecesref->{month};
814
815 ### format: printf "month %s -> Month %s\n", $piecesref->{month}, $month
816 }
817
818 if (defined ($piecesref->{day})) {
819 $day = $piecesref->{day};
820
821 ### format: printf "day %s -> Day %d\n", $piecesref->{day}, $day
822 }
823
824 $month = $mnames{lc(substr($month,0,3))} if ($month =~ /\D/);
825 $year-- if (($year_specified == 0) && ($this_month < $month));
826
827 ### format: printf STDERR "Final Year-Month-Day -> %04d-%02d-%02d\n", $year, $month, $day
828
829 $inforef->{$symbol, "date"} = sprintf "%02d/%02d/%04d", $month, $day, $year;
830 $inforef->{$symbol, "isodate"} = sprintf "%04d-%02d-%02d", $year, $month, $day;
831 }
832
833 ################################################################################
834 #
835 # Public Class or Object Methods
836 #
837 ################################################################################
838
839 # =======================================================================
840 # Helper function that can scale a field. This is useful because it
841 # handles things like ranges "105.4 - 108.3", and not just straight fields.
842 #
843 # The function takes a string or number to scale, and the factor to scale
844 # it by. For example, scale_field("1023","0.01") would return "10.23".
845
846 sub scale_field {
847 shift if ref $_[0]; # Shift off the object, if there is one.
848
849 my ($field, $scale) = @_;
850 my @chunks = split(/([^0-9.])/,$field);
851
852 for (my $i=0; $i < @chunks; $i++) {
853 next unless $chunks[$i] =~ /\d/;
854 $chunks[$i] *= $scale;
855 }
856 return join("",@chunks);
857 }
858
859 # =======================================================================
860 # currency (public object method)
861 #
862 # currency allows the conversion of one currency to another.
863 #
864 # Usage: $quoter->currency("USD","AUD");
865 # $quoter->currency("15.95 USD","AUD");
866 #
867 # undef is returned upon error.
868
869 sub currency {
870 my $this = ref($_[0]) ? shift : _dummy();
871
872 my ($from_code, $to_code) = @_;
873 return unless ($from_code and $to_code);
874
875 $from_code =~ s/^\s*(\d*\.?\d*)\s*//;
876 my $amount = $1 || 1;
877
878 $to_code = uc($to_code);
879 $from_code = uc($from_code);
880
881 return $amount if ($from_code eq $to_code); # Trivial case.
882
883 my $ua = $this->get_user_agent;
884
885 foreach my $rate (@{$this->{currency_rate_method}}) {
886 ### rate: ref($rate)
887 my $final = eval {
888 my ($from, $to) = $rate->multipliers($ua, $from_code, $to_code);
889
890 die("Failed to find currency rates for $from_code or $to_code") unless defined $from and defined $to;
891
892 ### to weight : $to
893 ### from weight: $from
894 ### amount : $amount
895
896 # Is from closest to (amount, to, amount * to)?
897 # (amount * to) / from
898 my $delta = abs($amount - $from);
899 my $result = ($amount/$from) * $to;
900 ### amount/from -> delta/result : ($delta, $result)
901 if ($delta > abs($to - $from)) {
902 $delta = abs($to - $from);
903 $result = ($to/$from) * $amount;
904 ### to/from -> delta/result : ($delta, $result)
905 }
906 if ($delta > abs($amount*$to - $from)) {
907 $delta = abs($amount*$to - $from);
908 $result = ($amount * $to)/$from;
909 ### (amount * to)/from -> delta/result : ($delta, $result)
910 }
911
912 return $result;
913 };
914
915 if ($@) {
916 ### Rate Error: chomp($@), $@
917 next;
918 }
919
920 return $final;
921 }
922
923 return;
924 }
925
926 # =======================================================================
927 # currency_lookup (public object method)
928 #
929 # search for available currency codes
930 #
931 # Usage:
932 # $currency = $quoter->currency_lookup();
933 # $currency = $quoter->currency_lookup( name => "Dollar");
934 # $currency = $quoter->currency_loopup( country => qw/denmark/i );
935 # $currency = $q->currency_lookup(country => qr/united states/i, number => 840);
936 #
937 # If more than one lookup parameter is given all must match for
938 # a currency to match.
939 #
940 # undef is returned upon error.
941
942 sub currency_lookup {
943 my $this = ref $_[0] ? shift : _dummy();
944
945 my %params = @_;
946 my $currencies = Finance::Quote::Currencies::known_currencies();
947
948 my %attributes = map {$_ => 1} map {keys %$_} values %$currencies;
949
950 for my $key (keys %params ) {
951 if ( ! exists $attributes{$key}) {
952 warn "Invalid parameter: $key";
953 return;
954 }
955 }
956
957 while (my ($tag, $check) = each(%params)) {
958 $currencies = {map {$_ => $currencies->{$_}} grep {_smart_compare($currencies->{$_}->{$tag}, $check)} keys %$currencies};
959 }
960
961 return $currencies;
962 }
963
964 # =======================================================================
965 # parse_csv (public object method)
966 #
967 # Grabbed from the Perl Cookbook. Parsing csv isn't as simple as you thought!
968 #
969 sub parse_csv
970 {
971 shift if (ref $_[0]); # Shift off the object if we have one.
972 my $text = shift; # record containing comma-separated values
973 my @new = ();
974
975 push(@new, $+) while $text =~ m{
976 # the first part groups the phrase inside the quotes.
977 # see explanation of this pattern in MRE
978 "([^\"\\]*(?:\\.[^\"\\]*)*)",?
979 | ([^,]+),?
980 | ,
981 }gx;
982 push(@new, undef) if substr($text, -1,1) eq ',';
983
984 return @new; # list of values that were comma-separated
985 }
986
987 # =======================================================================
988 # parse_csv_semicolon (public object method)
989 #
990 # Grabbed from the Perl Cookbook. Parsing csv isn't as simple as you thought!
991 #
992 sub parse_csv_semicolon
993 {
994 shift if (ref $_[0]); # Shift off the object if we have one.
995 my $text = shift; # record containing comma-separated values
996 my @new = ();
997
998 push(@new, $+) while $text =~ m{
999 # the first part groups the phrase inside the quotes.
1000 # see explanation of this pattern in MRE
1001 "([^\"\\]*(?:\\.[^\"\\]*)*)";?
1002 | ([^;]+);?
1003 | ;
1004 }gx;
1005 push(@new, undef) if substr($text, -1,1) eq ';';
1006
1007 return @new; # list of values that were comma-separated
1008 }
1009
1010 ###############################################################################
1011 #
1012 # Legacy Class Methods
1013 #
1014 ###############################################################################
1015
1016 sub sources {
1017 return get_methods();
1018 }
1019
1020 sub default_currency_fields {
1021 return get_default_currency_fields();
1022 }
1023
1024 ###############################################################################
1025 #
1026 # Legacy Class or Object Methods
1027 #
1028 ###############################################################################
1029
1030 # =======================================================================
1031 # set_currency (public object method)
1032 #
1033 # set_currency allows information to be requested in the specified
1034 # currency. If called with no arguments then information is returned
1035 # in the default currency.
1036 #
1037 # Requesting stocks in a particular currency increases the time taken,
1038 # and the likelyhood of failure, as additional operations are required
1039 # to fetch the currency conversion information.
1040 #
1041 # This method should only be called from the quote object unless you
1042 # know what you are doing.
1043
1044 sub set_currency {
1045 if (@_ == 1 or !ref($_[0])) {
1046 # Direct or class call - there is no class default currency
1047 return;
1048 }
1049
1050 my $this = shift;
1051 if (defined($_[0])) {
1052 $this->set_fetch_currency($_[0]);
1053 }
1054
1055 return $this->get_fetch_currency();
1056 }
1057
1058 # =======================================================================
1059 # Timeout code. If called on a particular object, then it sets
1060 # the timout for that object only. If called as a class method
1061 # (or as Finance::Quote::timeout) then it sets the default timeout
1062 # for all new objects that will be created.
1063
1064 sub timeout {
1065 if (@_ == 1 or !ref($_[0])) {
1066 # Direct or class call
1067 Finance::Quote::set_default_timeout(shift);
1068 return Finance::Quote::get_default_timeout();
1069 }
1070
1071 # Otherwise we were called through an object. Yay.
1072 # Set the timeout in this object only.
1073 my $this = shift;
1074 $this->set_timeout(shift);
1075 return $this->get_timeout();
1076 }
1077
1078 ###############################################################################
1079 #
1080 # Legacy Object Methods
1081 #
1082 ###############################################################################
1083
1084 # =======================================================================
1085 # failover (public object method)
1086 #
1087 # This sets/gets whether or not it's acceptable to use failover techniques.
1088
1089 sub failover {
1090 my $this = shift;
1091 my $value = shift;
1092
1093 $this->set_failover($value) if defined $value;
1094 return $this->get_failover();
1095 }
1096
1097 # =======================================================================
1098 # require_labels (public object method)
1099 #
1100 # Require_labels indicates which labels are required for lookups. Only methods
1101 # that have registered all the labels specified in the list passed to
1102 # require_labels() will be called.
1103 #
1104 # require_labels takes a list of required labels. When called with no
1105 # arguments, the require list is cleared.
1106 #
1107 # This method always succeeds.
1108
1109 sub require_labels {
1110 my $this = shift;
1111 my @labels = @_;
1112 $this->set_required_labels(\@labels);
1113 return;
1114 }
1115
1116 # =======================================================================
1117 # user_agent (public object method)
1118 #
1119 # Returns a LWP::UserAgent which conforms to the relevant timeouts,
1120 # proxies, and other settings on the particular Finance::Quote object.
1121 #
1122 # This function is mainly intended to be used by the modules that we load,
1123 # but it can be used by the application to directly play with the
1124 # user-agent settings.
1125
1126 sub user_agent {
1127 my $this = shift;
1128 return $this->get_user_agent();
1129 }
1130
1131 1;
1132
1133 __END__
1134
1135 =for comment README.md generated from lib/Finance/Quote.pm
1136
1137 =head1 NAME
1138
1139 Finance::Quote - Get stock and mutual fund quotes from various exchanges
1140
1141 =head1 SYNOPSIS
1142
1143 use Finance::Quote;
1144
1145 $q = Finance::Quote->new;
1146 %quotes = $q->fetch("nasdaq", @stocks);
1147
1148 =head1 DESCRIPTION
1149
1150 This module gets stock quotes from various internet sources all over the world.
1151 Quotes are obtained by constructing a quoter object and using the fetch method
1152 to gather data, which is returned as a two-dimensional hash (or a reference to
1153 such a hash, if called in a scalar context). For example:
1154
1155 $q = Finance::Quote->new;
1156 %info = $q->fetch("australia", "CML");
1157 print "The price of CML is ".$info{"CML", "price"};
1158
1159 The first part of the hash (eg, "CML") is referred to as the stock.
1160 The second part (in this case, "price") is referred to as the label.
1161
1162 =head2 LABELS
1163
1164 When information about a stock is returned, the following standard labels may
1165 be used. Some custom-written modules may use labels not mentioned here. If
1166 you wish to be certain that you obtain a certain set of labels for a given
1167 stock, you can specify that using require_labels().
1168
1169 ask Ask
1170 avg_vol Average Daily Vol
1171 bid Bid
1172 cap Market Capitalization
1173 close Previous Close
1174 currency Currency code for the returned data
1175 date Last Trade Date (MM/DD/YY format)
1176 day_range Day's Range
1177 div Dividend per Share
1178 div_date Dividend Pay Date
1179 div_yield Dividend Yield
1180 eps Earnings per Share
1181 errormsg If success is false, this field may contain the reason why.
1182 ex_div Ex-Dividend Date.
1183 exchange The exchange the information was obtained from.
1184 high Highest trade today
1185 isin International Securities Identification Number
1186 isodate ISO 8601 formatted date
1187 last Last Price
1188 low Lowest trade today
1189 method The module (as could be passed to fetch) which found this information.
1190 name Company or Mutual Fund Name
1191 nav Net Asset Value
1192 net Net Change
1193 open Today's Open
1194 p_change Percent Change from previous day's close
1195 pe P/E Ratio
1196 success Did the stock successfully return information? (true/false)
1197 time Last Trade Time
1198 type The type of equity returned
1199 volume Volume
1200 year_range 52-Week Range
1201 yield Yield (usually 30 day avg)
1202
1203 If all stock lookups fail (possibly because of a failed connection) then the
1204 empty list may be returned, or undef in a scalar context.
1205
1206 =head1 INSTALLATION
1207
1208 Please note that the Github repository is not meant for general users
1209 of Finance::Quote for installation.
1210
1211 If you downloaded the Finance-Quote-N.NN.tar.gz tarball from CPAN
1212 (N.NN is the version number, ex: Finance-Quote-1.50.tar.gz),
1213 run the following commands:
1214
1215 tar xzf Finance-Quote-1.50.tar.gz
1216 cd Finance-Quote-1.50.tar.gz
1217 perl Makefile.PL
1218 make
1219 make test
1220 make install
1221
1222 If you have the CPAN module installed:
1223 Using cpanm (Requires App::cpanminus)
1224
1225 cpanm Finance::Quote
1226
1227 or
1228 Using CPAN shell
1229
1230 perl -MCPAN -e shell
1231 install Finance::Quote
1232
1233 =head1 SUPPORT AND DOCUMENTATION
1234
1235 After installing, you can find documentation for this module with the
1236 perldoc command.
1237
1238 perldoc Finance::Quote
1239
1240 You can also look for information at:
1241
1242 =over
1243
1244 =item Finance::Quote GitHub project
1245
1246 https://github.com/finance-quote/finance-quote
1247
1248 =item Search CPAN
1249
1250 http://search.cpan.org/dist/Finance-Quote
1251
1252 =item The Finance::Quote home page
1253
1254 http://finance-quote.sourceforge.net/
1255
1256 =item The Finance::YahooQuote home page
1257
1258 http://www.padz.net/~djpadz/YahooQuote/
1259
1260 =item The GnuCash home page
1261
1262 http://www.gnucash.org/
1263
1264 =back
1265
1266 =head1 PUBLIC CLASS METHODS
1267
1268 Finance::Quote implements public class methods for constructing a quoter
1269 object, getting or setting default class values, and for listing available
1270 methods.
1271
1272 =head2 new
1273
1274 my $q = Finance::Quote->new()
1275 my $q = Finance::Quote->new('-defaults')
1276 my $q = Finance::Quote->new(timeout => 30)
1277 my $q = Finance::Quote->new('YahooJSON', fetch_currency => 'EUR')
1278 my $q = Finance::Quote->new('alphavantage' => {API_KEY => '...'})
1279 my $q = Finance::Quote->new(currency_rates => {order => ['ECB', 'Fixer'], 'fixer' => {API_KEY => '...'}});
1280
1281 Finance::Quote modules access a wide range of sources to provide quotes. A
1282 module provides one or more methods to fetch quotes. One method is usually the
1283 name of the module in lower case. Other methods, if provided, are descriptive
1284 names, such as 'canada', 'nasdaq', or 'nyse'.
1285
1286 A Finance::Quote object uses one or more methods to fetch quotes for
1287 securities.
1288
1289 C<new> constructs a Finance::Quote object and enables the caller to load only
1290 specific modules, set parameters that control the behavior of the fetch method,
1291 and pass method specific parameters.
1292
1293 =over
1294
1295 =item C<timeout =E<gt> T> sets the web request timeout to C<T> seconds
1296
1297 =item C<failover =E<gt> B> where C<B> is a boolean value indicating if failover in
1298 fetch is permitted
1299
1300 =item C<fetch_currency =E<gt> C> sets the desired currency code to C<C> for fetch
1301 results
1302
1303 =item C<currency_rates =E<gt> H> configures the order currency rate modules are
1304 consulted for exchange rates and currency rate module options
1305
1306 =item C<required_labels =E<gt> A> sets the required labels for fetch results to
1307 array C<A>
1308
1309 =item C<ModuleName> as a string is the name of a specific
1310 Finance::Quote::Module to load
1311
1312 =item C<methodname =E<gt> H> passes hash C<H> to methodname during fetch to
1313 configure the method
1314
1315 =back
1316
1317 With no arguments, C<new> creates a Finance::Quote object with the default
1318 methods. If the environment variable FQ_LOAD_QUOTELET is set, then the
1319 contents of FQ_LOAD_QUOTELET (split on whitespace) will be used as the argument
1320 list. This allows users to load their own custom modules without having to
1321 change existing code. If any method names are passed to C<new> or the flag
1322 '-defaults' is included in the argument list, then FQ_LOAD_QUOTELET is ignored.
1323
1324 When new() is passed one or more class name arguments, an object is created with
1325 only the specified modules loaded. If the first argument is '-defaults', then
1326 the default modules will be loaded first, followed by any other specified
1327 modules. Note that the FQ_LOAD_QUOTELET environment variable must begin with
1328 '-defaults' if you wish the default modules to be loaded.
1329
1330 Method names correspond to the Perl module in the Finance::Quote module space.
1331 For example, C<Finance::Quote-E<gt>new('ASX')> will load the module
1332 Finance::Quote::ASX, which provides the method "asx".
1333
1334 Some methods require API keys or have unique options. Passing 'method => HASH'
1335 to new() enables the caller to provide a configuration HASH to the corresponding
1336 method.
1337
1338 The key 'currency_rates' configures the Finanace::Quote currency rate
1339 conversion. By default, to maintain backward compatibility,
1340 Finance::Quote::CurrencyRates::AlphaVantage is used for currency conversion.
1341 This end point requires an API key, which can either be set in the environment
1342 or included in the configuration hash. To specify a different primary currency
1343 conversion method or configure fallback methods, include the 'order' key, which
1344 points to an array of Finance::Quote::CurrencyRates module names.
1345 Setting the environment variable FQ_CURRENCY will change the default
1346 endpoint used for currency conversion.
1347 See the documentation for the individual Finance::Quote::CurrencyRates
1348 modules to learn more.
1349
1350 =head2 get_default_currency_fields
1351
1352 my @fields = Finance::Quote::get_default_currency_fields();
1353
1354 C<get_default_currency_fields> returns the standard list of fields in a quote
1355 that are automatically converted during currency conversion. Individual modules
1356 may override this list.
1357
1358 =head2 get_default_timeout
1359
1360 my $value = Finance::Quote::get_default_timeout();
1361
1362 C<get_default_timeout> returns the current Finance::Quote default timeout in
1363 seconds for web requests. Finance::Quote does not specify a default timeout,
1364 deferring to the underlying user agent for web requests. So this function
1365 will return undef unless C<set_default_timeout> was previously called.
1366
1367 =head2 set_default_timeout
1368
1369 Finance::Quote::set_default_timeout(45);
1370
1371 C<set_default_timeout> sets the Finance::Quote default timeout to a new value.
1372
1373 =head2 get_methods
1374
1375 my @methods = Finance::Quote::get_methods();
1376
1377 C<get_methods> returns the list of methods that can be passed to C<new> when
1378 creating a quoter object and as the first argument to C<fetch>.
1379
1380 =head2 get_features
1381
1382 my %features = Finance::Quote::get_features();
1383
1384 C<get_features> returns a hash with three keys: quote_methods, quote_modules, and currency_modules.
1385
1386 $features{quote_methods} is a hash with key/value pairs of method_name => [array of module names]
1387 $features{quote_modules} is a hash with key/value pairs of module_name => [array of parameter names]
1388 $features{currency_modules} is a hash with key/value pairs of currency_module_name => [array of paramater names]
1389
1390 Parameter names are values that the module needs to function, such as API_KEY. Most
1391 modules will have an empty list. Modules with a parameter are configured when creating
1392 the Finance::Quote by passing the argument
1393
1394 'module_name_in_lower_case' => {paramter => value}
1395
1396 to Finance::Quote->new().
1397
1398 The keys of the $features{currency_modules} hash are the names of currency
1399 modules that can be used for currency conversion and the order in which the
1400 modules are used is controlled by the argument
1401
1402 currency_rates => {order => [subset of $features{currency_modules}]}
1403
1404 to Finance::Quote->new(). By default, AlphaVantage in used for
1405 currency conversion, "order" can be set to use other currency modules.
1406 The currency module used can also be changed by setting the FQ_CURRENCY
1407 environment variable. Please note that some of the alternate currency
1408 modules require API keys.
1409
1410
1411 =head1 PUBLIC OBJECT METHODS
1412
1413 =head2 B_to_billions
1414
1415 my $value = $q->B_to_billions("20B");
1416
1417 C<B_to_billions> is a utility function that expands a numeric string with a "B"
1418 suffix to the corresponding multiple of 1000000000.
1419
1420 =head2 decimal_shiftup
1421
1422 my $value = $q->decimal_shiftup("123.45", 1); # returns 1234.5
1423 my $value = $q->decimal_shiftup("0.25", 1); # returns 2.5
1424
1425 C<decimal_shiftup> moves a the decimal point in a numeric string the specified
1426 number of places to the right.
1427
1428 =head2 fetch
1429
1430 my %stocks = $q->fetch("alphavantage", "IBM", "MSFT", "LNUX");
1431 my $hashref = $q->fetch("nasdaq", "IBM", "MSFT", "LNUX");
1432
1433 C<fetch> takes a method as its first argument and the remaining arguments are
1434 treated as securities. If the quoter C<$q> was constructed with a specific
1435 method or methods, then only those methods are available.
1436
1437 When called in an array context, a hash is returned. In a scalar context, a
1438 reference to a hash will be returned. The keys for the returned hash are
1439 C<{SECURITY,LABEL}>. For the above example call, C<$stocks{"IBM","high"}> is
1440 the high value for IBM.
1441
1442 $q->get_methods() returns the list of valid methods for quoter object $q. Some
1443 methods specify a specific Finance::Quote module, such as 'alphavantage'. Other
1444 methods are available from multiple Finance::Quote modules, such as 'nasdaq'.
1445 The quoter failover over option determines if multiple modules are consulted
1446 for methods such as 'nasdaq' that more than one implementation.
1447
1448 =head2 get_failover
1449
1450 my $failover = $q->get_failover();
1451
1452 Failover is when the C<fetch> method attempts to retrieve quote information for
1453 a security from alternate sources when the requested method fails.
1454 C<get_failover> returns a boolean value indicating if the quoter object will
1455 use failover or not.
1456
1457 =head2 set_failover
1458
1459 $q->set_failover(False);
1460
1461 C<set_failover> sets the failover flag on the quoter object.
1462
1463 =head2 get_fetch_currency
1464
1465 my $currency = $q->get_fetch_currency();
1466
1467 C<get_fetch_currency> returns either the desired currency code for the quoter
1468 object or undef if no target currency was set during construction or with the
1469 C<set_fetch_currency> function.
1470
1471 =head2 set_fetch_currency
1472
1473 $q->set_fetch_currency("FRF"); # Get results in French Francs.
1474
1475 C<set_fetch_currency> method is used to request that all information be
1476 returned in the specified currency. Note that this increases the chance
1477 stock-lookup failure, as remote requests must be made to fetch both the stock
1478 information and the currency rates. In order to improve reliability and speed
1479 performance, currency conversion rates are cached and are assumed not to change
1480 for the duration of the Finance::Quote object.
1481
1482 See the introduction to this page for information on how to configure the
1483 source of currency conversion rates.
1484
1485 =head2 get_required_labels
1486
1487 my @labels = $q->get_required_labels();
1488
1489 C<get_required_labels> returns the list of labels that must be populated for a
1490 security quote to be considered valid and returned by C<fetch>.
1491
1492 =head2 set_required_labels
1493
1494 my $labels = ['close', 'isodate', 'last'];
1495 $q->set_required_labels($labels);
1496
1497 C<set_required_labels> updates the list of required labels for the quoter object.
1498
1499 =head2 get_timeout
1500
1501 my $timeout = $q->get_timeout();
1502
1503 C<get_timeout> returns the timeout in seconds the quoter object is using for
1504 web requests.
1505
1506 =head2 set_timeout
1507
1508 $q->set_timeout(45);
1509
1510 C<set_timeout> updated the timeout in seconds for the quoter object.
1511
1512 =head2 store_date
1513
1514 $quoter->store_date(\%info, $stocks, {eurodate => '06/11/2020'});
1515
1516 C<store_date> is used by modules to consistent store date information about
1517 securities. Given the various pieces of a date, this function figures out how to
1518 construct a ISO date (yyyy-mm-dd) and US date (mm/dd/yyyy) and stores those
1519 values in C<%info> for security C<$stock>.
1520
1521 =head2 get_user_agent
1522
1523 my $ua = $q->get_user_agent();
1524
1525 C<get_user_agent> returns the LWP::UserAgent the quoter object is using for web
1526 requests.
1527
1528 =head2 isoTime
1529
1530 $q->isoTime("11:39PM"); # returns "23:39"
1531 $q->isoTime("9:10 AM"); # returns "09:10"
1532
1533 C<isoTime> returns an ISO formatted time.
1534
1535 =head1 PUBLIC CLASS OR OBJECT METHODS
1536
1537 The following methods are available as class methods, but can also be called
1538 from Finance::Quote objects.
1539
1540 =head2 scale_field
1541
1542 my $value = Finance::Quote->scale_field('1023', '0.01')
1543
1544 C<scale_field> is a utility function that scales the first argument by the
1545 second argument. In the above example, C<value> is C<'10.23'>.
1546
1547 =head2 currency
1548
1549 my $value = $q->currency('15.95 USD', 'AUD');
1550 my $value = Finance::Quote->currency('23.45 EUR', 'RUB');
1551
1552 C<currency> converts a value with a currency code suffix to another currency
1553 using the current exchange rate as determined by the
1554 Finance::Quote::CurrencyRates method or methods configured for the quoter $q.
1555 When called as a class method, Finance::Quote::AlphaVantage is the default,
1556 which requires an API key. See the introduction for information on configuring
1557 currency rate conversions and see Finance::Quote::CurrencyRates::AlphaVantage
1558 for information about the API key.
1559
1560 =head2 currency_lookup
1561
1562 my $currency = $quoter->currency_lookup();
1563 my $currency = $quoter->currency_lookup( name => "Caribbean");
1564 my $currency = $quoter->currency_loopup( country => qw/denmark/i );
1565 my $currency = $q->currency_lookup(country => qr/united states/i, number => 840);
1566
1567 C<currency_lookup> takes zero or more constraints and filters the list of
1568 currencies known to Finance::Quote. It returns a hash reference where the keys
1569 are ISO currency codes and the values are hash references containing metadata
1570 about the currency.
1571
1572 A constraint is a key name and either a scalar or regular expression. A
1573 currency satisfies the constraint if its metadata hash contains the constraint
1574 key and the value of that metadata field matches the regular expression or
1575 contains the constraint value as a substring. If the metadata field is an
1576 array, then it satisfies the constraint if any value in the array satisfies the
1577 constraint.
1578
1579 =head2 parse_csv
1580
1581 my @list = Finance::Quote::parse_csv($string);
1582
1583 C<parse_csv> is a utility function for splitting a comma separated value string
1584 into a list of terms, treating double-quoted strings that contain commas as a
1585 single value.
1586
1587 =head2 parse_csv_semicolon
1588
1589 my @list = Finance::Quote::parse_csv_semicolon($string);
1590
1591 C<parse_csv> is a utility function for splitting a semicolon separated value string
1592 into a list of terms, treating double-quoted strings that contain semicolons as a
1593 single value.
1594
1595 =head1 LEGACY METHODS
1596
1597 =head2 default_currency_fields
1598
1599 Replaced with get_default_currency_fields().
1600
1601 =head2 sources
1602
1603 Replaced with get_methods().
1604
1605 =head2 failover
1606
1607 Replaced with get_failover() and set_failover().
1608
1609 =head2 require_labels
1610
1611 Replaced with get_required_labels() and set_required_labels().
1612
1613 =head2 user_agent
1614
1615 Replaced with get_user_agent().
1616
1617 =head2 set_currency
1618
1619 Replaced with get_fetch_currency() and set_fetch_currency().
1620
1621 =head1 ENVIRONMENT
1622
1623 Finance::Quote respects all environment that your installed version of
1624 LWP::UserAgent respects. Most importantly, it respects the http_proxy
1625 environment variable.
1626
1627 =head1 USAGE COUNTER
1628
1629 A simple usage counter has been enabled. Other than the user's IP address, Finance::Quote version, and which method was used, no other data is collected. To opt out of your usage being counted, set the environment variable "FQ_NOCOUNT".
1630
1631 =head1 BUGS
1632
1633 The caller cannot control the fetch failover order.
1634
1635 The two-dimensional hash is a somewhat unwieldly method of passing around
1636 information when compared to references
1637
1638 =head1 COPYRIGHT & LICENSE
1639
1640 Copyright 1998, Dj Padzensky
1641 Copyright 1998, 1999 Linas Vepstas
1642 Copyright 2000, Yannick LE NY (update for Yahoo Europe and YahooQuote)
1643 Copyright 2000-2001, Paul Fenwick (updates for ASX, maintenance and release)
1644 Copyright 2000-2001, Brent Neal (update for TIAA-CREF)
1645 Copyright 2000 Volker Stuerzl (DWS)
1646 Copyright 2001 Rob Sessink (AEX support)
1647 Copyright 2001 Leigh Wedding (ASX updates)
1648 Copyright 2001 James Treacy (TD Waterhouse support)
1649 Copyright 2008 Erik Colson (isoTime)
1650
1651 This program is free software; you can redistribute it and/or modify it under
1652 the terms of the GNU General Public License as published by the Free Software
1653 Foundation; either version 2 of the License, or (at your option) any later
1654 version.
1655
1656 Currency information fetched through this module is bound by the terms and
1657 conditons of the data source.
1658
1659 Other copyrights and conditions may apply to data fetched through this module.
1660 Please refer to the sub-modules for further information.
1661
1662 =head1 AUTHORS
1663
1664 The following list are those contributors with 5 or more commits in the
1665 GitHub repository.
1666 Please see the Git log for all the authors who have helped with
1667 Finance::Quote.
1668
1669 Erik Colson <[email protected]>
1670 Bruce Schuck <[email protected]>
1671 Paul Fenwick <[email protected]>
1672 Vincent Lucarelli <[email protected]>
1673 David Hampton <[email protected]>
1674 jvolkening <[email protected]>
1675 Pawel Konieczny <[email protected]>
1676 Mike Alexander <[email protected]>
1677 AndreJ <[email protected]>
1678 Vinay S Shastry <[email protected]>
1679 Bradley Dean <[email protected]>
1680 Brent Neal <[email protected]>
1681 Jacinta Richardson <[email protected]>
1682 e-dorigatti <[email protected]>
1683 goodvibes2 <[email protected]>
1684 Paul Howarth <[email protected]>
1685 Sam Morris <[email protected]>
1686 Linas Vepstas <[email protected]>
1687 Rajan Vaswani <[email protected]>
1688 Hiranya Samarasekera <[email protected]>
1689 Manuel Friedli <[email protected]>
1690
1691 The Finance::Quote home page can be found at
1692 http://finance-quote.sourceforge.net/
1693
1694 The Finance::YahooQuote home page can be found at
1695 http://www.padz.net/~djpadz/YahooQuote/
1696
1697 The GnuCash home page can be found at
1698 http://www.gnucash.org/
1699
1700 =head1 SEE ALSO
1701
1702 Finance::Quote::CurrencyRates::AlphaVantage,
1703 Finance::Quote::CurrencyRates::CurrencyFreaks,
1704 Finance::Quote::CurrencyRates::ECB,
1705 Finance::Quote::CurrencyRates::FinanceAPI,
1706 Finance::Quote::CurrencyRates::Fixer,
1707 Finance::Quote::CurrencyRates::Frankfurter,
1708 Finance::Quote::CurrencyRates::OpenExchange,
1709 Finance::Quote::CurrencyRates::TwelveData,
1710 Finance::Quote::CurrencyRates::UniRate,
1711 Finance::Quote::CurrencyRates::YahooJSON,
1712 Finance::Quote::ASEGR,
1713 Finance::Quote::ASX,
1714 Finance::Quote::BorsaItaliana,
1715 Finance::Quote::BSEIndia,
1716 Finance::Quote::Bourso,
1717 Finance::Quote::BVB,
1718 Finance::Quote::CSE,
1719 Finance::Quote::Comdirect,
1720 Finance::Quote::Consorsbank,
1721 Finance::Quote::Currencies,
1722 Finance::Quote::Deka,
1723 Finance::Quote::FinanceAPI,
1724 Finance::Quote::Finanzpartner,
1725 Finance::Quote::Finnhub,
1726 Finance::Quote::Fondsweb,
1727 Finance::Quote::Fool,
1728 Finance::Quote::FTfunds,
1729 Finance::Quote::GoldMoney,
1730 Finance::Quote::GoogleWeb,
1731 Finance::Quote::IndiaMutual,
1732 Finance::Quote::MarketWatch,
1733 Finance::Quote::MorningstarJP,
1734 Finance::Quote::NSEIndia,
1735 Finance::Quote::NZX,
1736 Finance::Quote::OnVista,
1737 Finance::Quote::SIX,
1738 Finance::Quote::StockData,
1739 Finance::Quote::Stooq,
1740 Finance::Quote::SwissFundData,
1741 Finance::Quote::TSP,
1742 Finance::Quote::TMX,
1743 Finance::Quote::TesouroDireto,
1744 Finance::Quote::TreasuryDirect,
1745 Finance::Quote::TwelveData,
1746 Finance::Quote::Union,
1747 Finance::Quote::USBonds,
1748 Finance::Quote::YahooJSON,
1749 Finance::Quote::YahooWeb,
1750 Finance::Quote::XETRA,
1751 Finance::Quote::ZA
1752
1753 You should have received the Finance::Quote hacker's guide with this package.
1754 Please read it if you are interested in adding extra methods to this package.
1755 The latest hacker's guide can also be found on GitHub at
1756 https://github.com/finance-quote/finance-quote/blob/master/Documentation/Hackers-Guide
1757
1758 =head1 DONATIONS
1759
1760 While the contributors to Finance::Quote are happy to volunteer their time and resources on this project, donations are helpful and great way to say thank you. So far the only real cost to the team is domain registration for finance-quote.org. However, some operating systems and hardware upgrades do have a cost. Access to the latest or current environments is needed for development and testing. Upgrades to the latest MS Windows often includes a cost, and recently Apple's move to ARM/M1/M2 CPUs has stifled some contributors' ability to assist. With that in mind, you can send donations to the email address [email protected] through PayPal. If it's for a particular contributor, please indicate in a note while submitting the donation through PayPal.
1761
1762 Additionally, Bitcoin donations can be received at 37Bg4EMAp575j4iL9jHv1ZhDgiropU38jY.
1763
1764 =cut