Debian Codegraph @

CONTRIBUTING.md

raw
1 # Introduction
2
3 This is a guide for those who wish to contribute to Finance::Quote,
4 or create their own Finance::Quote pluggable module. As an open project,
5 Finance::Quote appreciates contributions from the community.
6
7 The initial version of this document is derived from the
8 [Hackers Guide](https://github.com/finance-quote/finance-quote/blob/master/Documentation/Hackers-Guide)
9
10 This guide assumes that you are familiar with Perl.
11
12 ## Finance::Quote People
13
14 - Core Team
15
16 These people are the only people allowed to merge pull requests.
17 A subset of these people have the permissions to push releases to
18 the CPAN Finance::Quote namespace.
19
20 - Contributors
21
22 This team will help review issues and pull requests.
23
24 - You!
25
26 Many features and bug fixes have come from the open source community
27 as a whole. Finance::Quote depends on you as just as much as it does
28 the team members.
29
30 # Ways to Help
31
32 - Coding
33
34 The primary way to contribute is obviously coding. That could mean
35 addressing reported issues, improving existing modules, or
36 creating a new module to retrieve data.
37
38 - Documentation
39
40 But you don't need to be a Perl programmer to contribute! We welcome
41 updates to the documentation on the Github repository, or the
42 pages at Sourceforge ([https://sourceforge.net/projects/finance-quote/](https://sourceforge.net/projects/finance-quote/)
43 and [https://finance-quote.sourceforge.net/](https://finance-quote.sourceforge.net/)).
44
45 - Discussions
46
47 There is also more of an informal way to help by joining any
48 of the Finance::Quote
49 [Discussions](https://github.com/finance-quote/finance-quote/discussions)
50 as well as the mailing lists hosted at Sourceforge
51 ([https://sourceforge.net/p/finance-quote/mailman/](https://sourceforge.net/p/finance-quote/mailman/)).
52
53 # Setup a Development Environment
54
55 To develop and test modules, you need a clone of the Finance-Quote
56 git repository, a recent version of perl, and the Dist::Zilla module
57 and its dependencies. The following steps provide a recipe for setup.
58
59 - A: Clone the git repo
60
61 $ git clone https://github.com/finance-quote/finance-quote.git
62
63
64 - B: (Optional) Install latest stable copy of perl in ~/perl5
65
66 $ curl -L https://install.perlbrew.pl | bash
67 $ echo "source ~/perl5/perlbrew/etc/bashrc" >> ~/.bash_profile # or the equivalent for your shell
68 $ perlbrew --notest install perl-5.28.1 # --notest is risky, but significant speeds installation
69 $ perlbrew switch perl-5.28.1
70 $ perlbrew install-cpanm
71
72 - C: Install Dist::Zilla
73
74 $ cpanm install Dist::Zilla
75
76 # inside the finance-quote directory
77 # remove --missing to install missing & upgrade existing required package
78
79 $ dzil authordeps --missing | cpanm --notest
80 $ dzil listdeps --missing | cpanm --notest
81
82 $ cpanm install Data::Dumper::Perltidy Smart::Comments
83
84
85 - D: Test out finance-quote
86
87 # Light-weight test mode that skips all online tests
88
89 $ dzil test
90
91 # To run all the skipped tests, you need three environment variables:
92 # TEST_AUTHOR - when set, tests are run to check for required modules
93 # ONLINE_TEST - when set, online tests are executed
94 # ALPHAVANTAGE_API_KEY - free API key available from https://www.alphavantage.co
95 #
96 # Using bash syntax to set environment variables
97
98 $ cpanm Test::Pod Test::Pod::Coverage Test::Kwalitee Test::Perl::Critic
99
100 # This runs a few code checks, including best practices as noted
101 # in "Perl Best Practices".
102
103 $ TEST_AUTHOR=1 dzil test
104
105 # Be aware of the limit of API keys. Running many tests may consume
106 # the maximum number of allowed queries.
107
108 $ TEST_AUTHOR=1 ONLINE_TEST=1 TEST_ALPHAVANTAGE_API_KEY=<YOUR API KEY> dzil test
109
110 # To do an online test for one module
111
112 $ ONLINE_TEST=1 dzil run prove -lv t/iexcloud.t
113
114 # Use prove to during test development - it is fast
115
116 $ prove -lv t/fq-class-methods.t
117
118 # Use perlcritic on your module
119
120 $ perlcritic lib/Finance/Quote/YourModule.pm
121
122 # How to write a Finance::Quote module
123
124 Finding a source of information, and writing code to parse and interpret
125 that information is a difficult task. As such, we've aimed to make
126 writing a Finance::Quote module as easy as possible. There are only
127 a few simple rules you need to follow:
128
129 ## The package name
130
131 Finance::Quote expects that its loadable modules will be in the
132 Finance::Quote namespace somewhere. Hence, if you were writing
133 a module called "DodgyBank" that returned information on DodgyBank's
134 managed funds, a reasonable name for that module would be
135 Finance::Quote::DodgyBank.
136
137 ## The methodinfo() subroutine
138
139 Your module must have a subroutine named methodinfo(). Future versions
140 of GnuCash may use this to dynamically determine the data sources
141 available. The subroutine returns a nested data structure of the
142 method(s) defined in the module, along with additional information.
143
144 In this example, the main method is "foobar". But this method can be used
145 for failover methods "usa", "nyse", or "nasdaq".
146
147 sub methodinfo {
148 return (
149 foobar => $METHODHASH,
150 usa => $METHODHASH,
151 nyse => $METHODHASH,
152 nasdaq => $METHODHASH,
153 );
154 }
155
156 The information for the method in contained in another data structure.
157 In our example, "$METHODHASH". This data structure will contain a brief name,
158 any features such as needing a API key, and the labels (data fields) the
159 method will returns.
160
161 our $DISPLAY = 'FooBar';
162 our $FEATURES = {'API_KEY' => 'registered user API key'};
163 our @LABELS = qw/date isodate open high low close volume last net p_change/;
164 our $METHODHASH = {subroutine => \&foobar,
165 display => $DISPLAY,
166 labels => \@LABELS,
167 features => $FEATURES};
168
169 It is uncommon, but some modules may contain 2 or more different methods.
170 Not to be confused with failover methods.
171 In this example, a module to retrieve data from "Dodgy Bank, USA" may
172 have a method defined for funds and another for bonds. Both require an
173 API key.
174
175 our $FUNDSDISPLAY = 'Dodgy Bank Funds';
176 our $FEATURES = {'API_KEY' => 'registered user API key'};
177 our @LABELS = qw/date isodate open high low close volume last net p_change/;
178 our $FUNDSHASH = {subroutine => \&funds,
179 display => $FUNDSDISPLAY,
180 labels => \@LABELS,
181 features => $FEATURES};
182
183 our $BONDSDISPLAY = 'Dodgy Bank Bonds';
184 our $BONDSHASH = {subroutine => \&bonds,
185 display => $BONDSDISPLAY,
186 labels => \@LABELS,
187 features => $FEATURES};
188
189 sub methodinfo {
190 return (
191 dodgyfunds => $FUNDSHASH,
192 dodgybonds => $BONDSHASH,
193 );
194 }
195
196 ## The methods() subroutine
197
198 Your module must have a subroutine named methods(). This function will
199 be called by the Finance::Quote harness when it loads your module, and
200 is used to determine which methods your module provides. The methods()
201 function must return a hash of method names and subroutine references.
202 For example, if you had written a module which provides access to
203 DodgyBank's managed funds, you might have the following
204
205 package Finance::Quote::DodgyBank;
206 .
207 .
208 sub methods {
209 my %m = methodinfo(); return map {$_ => $m{$_}{subroutine} } keys %m;
210 }
211
212 This would indicate that your package provides methods for
213 "dodgyfunds" and "dodgyloans", and that the subroutines
214 "funds" and "loans" should be called to access that information.
215
216 The following method names should be used for the following information
217 sources:
218
219 Method-Name Source
220 ---------------------------------------------------------
221 australia Australian Stocks
222 canada Canadian Stocks
223 europe European Stocks
224 fidelity Fidelity Investments
225 nasdaq NASDAQ
226 nyse New York Stock Exchange
227 tiaacref TIAA-CREF
228 troweprice T. Rowe. Price
229 usa USA Stocks
230
231 Method names should be lower-case, consist of alphanumeric characters
232 (including underscore) only, and always begin with a letter. This is
233 not enforced, but future versions of the Finance::Quote framework may
234 rely upon it.
235
236 It's strongly recommended that you also provide a unique name for your
237 method, in case you (or others) wish to call that method exclusively
238 in code. Hence if you had written a module to fetch information from
239 the NYSE from Yohoo! and named the subroutine "yohoo", your methodinfo subroutine may look like:
240
241 sub methodinfo {
242 return (
243 yohoo => $METHODHASH,
244 nyse => $METHODHASH,
245 );
246 }
247
248 This means that people who only want to use your function can use
249 $quoter->fetch('yohoo',@stocks), but those who don't care where
250 their NYSE stock information is fetched from can use
251 $quoter->fetch('nyse',@stocks). The first form allows you to know exactly
252 where the information is coming from. In the second, failover methods mean
253 that many different functions could be used to fetch the stock information,
254 not just the one you have defined.
255
256 ## The functions specified by methods()
257
258 The functions referred to by methods() will be passed a Finance::Quote
259 object when called, and a list of zero or more symbol names. The
260 Finance::Quote object provides the following ready-to-use methods:
261
262 user_agent(); # Provides a ready-to-use LWP::UserAgent
263
264 parse_csv(); # Parses a list of comma-separated values
265 # and returns an array.
266
267 The user\_agent() method should be used if possible to fetch the information,
268 as it should be already configured to use the timeout, proxy, and other
269 settings requested by the calling program.
270
271 Your function should return a two-dimensional hash as specified in the
272 Finance::Quote man-page. Eg:
273
274 $hash{$symbol,'last'} = $last_price;
275 $hash{$symbol,'name'} = $stock_name;
276 # etc etc.
277
278 When returning your hash, you should check the context that your
279 function was called in. If it was called in a scalar context, then
280 you should return a hashref instead. This can be easily done
281 with the following:
282
283 return wantarray() ? %hash : \%hash;
284
285 It is ESSENTIAL that your hash contain a true value for {$symbol,'success'}
286 for information that has been successfully obtained. If the information
287 was not obtained for any reason, then {$symbol,'success'} should
288 be set to a false value (preferably 0), and a human-readable error
289 message placed in {$symbol,'errormsg'}. The following code snippet
290 demonstrates this:
291
292 sub funds {
293
294 my $quoter = shift; # The Finance::Quote object.
295 my @stocks = @_;
296 my %info;
297
298 my $DODGY_URL = "http://dodgybank.xxx/funds.csv?";
299
300 my $ua = $quoter->user_agent; # This gives us a user-agent
301 # with timeouts, proxies,
302 # etc already configured.
303
304 my $response = $ua->request(GET $DODGY_URL);
305 unless ($response->is_success) {
306 foreach my $stock (@stocks) {
307 $info{$stock,"success"} = 0;
308 $info{$stock,"errormsg"} = "HTTP failure";
309 }
310 return wantarray ? %info : \%info;
311 }
312
313 # Do stuff with the information returned....
314
315 }
316
317 It is valid to use "return" with no arguments if all stock lookups failed,
318 however this does not provide any information as to WHY the lookups
319 failed. If at all possible, the errormsg labels should be set.
320
321 It is also very very strongly recommended that you place your module's
322 name in the {$stock,"source"} field. This allows others to check where
323 information was obtained, and to use it appropriately.
324
325 ## The parameters() subroutine - Modules requiring API Keys
326
327 Some data sources require an API Key (sometimes called a token) in
328 order to access the securities or exchange data. AlphaVantage.pm
329 is one example.
330
331 In order to assist programs using Finance::Quote to identify those
332 modules that require an API Key please include this function if
333 your module is using a data source that requires a key/token.
334
335 sub parameters {
336 return ('API_KEY');
337 }
338
339 ## Currency
340
341 Finance::Quote has support for multiple currencies and for currency
342 conversion. As long as you provide a little bit of information about
343 the information you are returning, the Finance::Quote framework can
344 do all the hard stuff for you.
345
346 If you are returning information on a stock in a particular currency,
347 then you can enter the ISO currency code into the "currency" field
348 associated with the stock. Eg:
349
350 $info{$stock,"currency"} = "AUD"; # Australian Dollars
351
352 If the information you are returning does not have a currency
353 (because it's an index like the Dow Jones Industrial or the
354 All Oridinaries, or because you're returning percentages) then
355 you should not set the currency field for that stock. Finance::Quote
356 knows not to attempt currency conversion for stocks without
357 a currency field.
358
359 If you do have a currency field, then by default Finance::Quote will
360 arrange for the automatic conversion of a number of fields. By
361 default, these fields are last, high, low, net, bid, ask, close, open,
362 day\_range, year\_range, eps, div, cap, nav and price. Of course,
363 there may be some cases where this set is not appropriate, or where there
364 are extra fields that should be converted. This can be indicated
365 by writing a function called "currency\_fields()" in your module,
366 that returns a list of fields that can undergo currency conversion.
367 Eg:
368
369 sub currency_fields {
370 return qw/high low price bid/;
371 }
372
373 currency\_fields() will be passed a Finance::Quote object as its
374 first argument, and a method called default\_currency\_fields()
375 is available through this object. This is useful if you want
376 to use the defaults, but also add some of your own:
377
378 sub currency_fields {
379 my $quoter = shift;
380 return ($quoter->default_currency_fields, "commission");
381 }
382
383 In the example above, the default fields would be available for currency
384 conversion, but the "commission" field would also be converted.
385
386 ## Development & Debugging Code
387
388 There are multiple ways to include extra code in Perl modules to facilitate
389 development and debugging. For Finance::Quote modules, please use the following
390 strategy that uses a combination of a DEBUG constant and the Smart::Comments
391 module. If DEBUG is in the environment and set to a value that Perl evaluates
392 to true, then Smart::Comments is active and code blocks wrapped with if(DEBUG)
393 are also active. Otherwise, all the debugging code disappears during
394 compilation.
395
396 use strict; # use strict & warnings FIRST
397 use warnings;
398
399 use constant DEBUG => $ENV{DEBUG}; # create a constant from the environment
400
401 use if DEBUG, 'Smart::Comments'; # conditionally use Smart::Comments
402 use if DEBUG, 'Another::Module'; # example module only needed for debugging
403
404 use LWP::UserAgent; # and finally production module dependencies
405
406 my %h = ('a' => 1); # just an example variable
407
408 # These first two lines are always a comment. The third line
409 # prints a debugging string if DEBUG is in the environment.
410 ### [<now>] h: \%h
411
412 # For more complicated debugging, the following if-block
413 # will disappear during compilation because of constant folding.
414 if (DEBUG) {
415 print "More complex debugging code\n";
416 }
417
418 ## Dates
419
420 Do not parse dates directly in your module. Instead you should use
421 the function $q->store\_date(), which handles a variety of date
422 formats. In its simplest form, you simply tell the function what
423 format the date is in and it handles all the parsing. The code should
424 look similar to this:
425
426 $quoter->store_date(\%info, $stock, {eurodate => @$row[1]});
427
428 If the web site doesn't have a data available, somply call the
429 function this way:
430
431 $quoter->store_date(\%info, $stock, {today => 1});
432
433 See the documentation in Quote.pm for more information.
434
435 ## Please don't die
436
437 Finance::Quote should always return data, even if no data was retrieved
438 for any of the securities. Instead, set "success" to 0 and an error
439 message ("errormsg") for all of the requested securities.
440
441 ## Things to avoid
442
443 Some sources of information will provide more stock information than
444 requested. Some code may rely upon your code only returning information
445 about the stocks that the caller requested. As such, you should
446 never return information about stocks that were not requested, even
447 if you fetch and/or process that information.
448
449 ## Editor Settings
450
451 As an OpenSource project, there have been many contributors to Finance::Quote.
452 Which means a variety of text editors and coding styles can be found.
453 We ask that if a module is being modified, that contributors follow
454 the formatting and indenting style of the original author.
455
456 One way to satisfy this is to take note of things like vi/vim modeline
457 commands or Emacs file variables that previous authors may have included.
458
459 For example I primarily use vim and include the following modeline near
460 the top of most scripts and code.
461
462 `# vi: set ts=4 sw=4 noai ic expandtab showmatch showmode:`
463
464 The equivalent for Emacs may be:
465
466 `# -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; case-fold-search: nil; -*-`
467
468 ## Using your new module
469
470 Using your new module is easy. Normally when using Finance::Quote you'd
471 do something like the following:
472
473 use Finance::Quote;
474 my $quoter = Finance::Quote->new();
475
476 To use your new module, simply specify the module name (without
477 the Finance::Quote prefix) in the new function. Hence:
478
479 use Finance::Quote;
480 my $quoter = Finance::Quote->new("DodgyBank");
481
482 The DodgyBank methods will now be available:
483
484 my %loaninfo = $quoter->fetch("dodgyloans","car","boat","house");
485 my %fundinfo = $quoter->fetch("dodgyfunds","lotto","shares");
486
487 The resulting Finance::Quote object will also arrange for your functions
488 to be callable without using fetch. This syntax is strongly discouraged,
489 as it results in pollution of the Finance::Quote namespace and provides
490 little advantages over the fetch() method:
491
492 my %loaninfo = $quoter->dodgyloans("car","boat","loan");
493
494 This mainly exists to maintain compatibility with previous versions of
495 Finance::Quote.
496
497 # How to write a Finance::Quote::CurrencyRates module
498
499 Currency Rate modules carryout a single task: Given two currencies, return
500 multipliers that describe the relative value of the currencies. In the
501 simplest case, one multiplier is "1.0" and the other multiplier is the exchange
502 rate between the two currencies. In the other case, the multipliers reflect the
503 relative value of each currency to a third base currency.
504
505 For example, on 2020-10-30, the European Central Bank reported that 1.1698 USD
506 (United States Dollar) was equivalent to 1.00 EUR (Euro). It also reported that
507 0.90208 GBP (Pound Sterling) was equivalent to 1.00 EUR. To convert from USD to
508 GBP, the following from/to multipliers are equivalent:
509
510 from to Base Currency
511 -------- -------- -------------
512 1.16980 0.90208 EUR
513 1.00000 0.77114 USD
514 1.29678 1.00000 GBP
515
516 Depending on the source of the currency rates, it may be more convenient for a
517 currency rate module to return multipliers that are relative to a third
518 currency (first row), the conversion rate (the second row), or the inverse
519 conversion rate (the third row).
520
521 Currency rate modules should avoid carrying out arithmetic and leave it to
522 Finance::Quote to use the multipliers to compute the final conversion value.
523
524 ## The package name
525
526 Currency rate modules belong in the Finance::Quote::CurrencyRates namespace and
527 the name of the module should be descriptive. Use PascalCase (upper CamelCase)
528 for the module name.
529
530 ## The new() constructor
531
532 Currency rate modules are called from a Finance::Quote quoter object when
533 currency conversion is either explicitly requested from a caller or to convert
534 a fetched security price to a user specified currency. When instantiating a
535 quoter object, the caller may pass module specific parameters. Suppose the
536 currency rate module ExampleRates requires an API key and also optionally
537 supports caching rates during the lifetime of the quoter object. Then the
538 code
539
540 my $q = Finance::Quote->new('currency_rates' =>
541 {order => ['ExampleRates', 'ECB'],
542 examplerates => {API_KEY => 'x01234566',
543 cache => True}});
544
545 instantiates a quoter that uses ExampleRates first and falls back the ECB
546 for currency rates. When ExampleRates is used, the API\_KEY can cache options
547 are configured through a module specific hash.
548
549 Finance::Quote passes just the hash containing the API\_KEY and cache key/value
550 pairs to ExampleRates->new() as a hash reference. If the caller does not
551 specify an ExampleRates key in the currency\_rates hash, then ExampleRates->new()
552 is called with no arguments. ExamplesRates may, but is not required, to
553 alternately read the API key from an environment variable.
554
555 Clearly document all currency rate module options in the POD documentation for
556 the module.
557
558 ## The multipliers() function
559
560 Finance::Quote calls the currency rate object method multipliers() with the
561 arguments (object, user\_agent, from, to), where
562
563 object was previously instantiated with a call to new()
564 user_agent is a LWP::UserAgent
565 from is an ISO currency code
566 to is an ISO currency code
567
568 multipliers() must a pair of multipliers (from\_multiplier, to\_multiplier),
569 where
570
571 from_multiplier is a floating point value
572 to_multiplier is a floating point value
573
574 and to\_multiplier/from\_multiplier will convert a value in currency "from"
575 into currency "to".
576
577 On error, multipliers() must return undef.
578
579 # How to contribute your module to the world
580
581 Check list:
582
583 - Created a well-named module file in the Finance directory tree.
584 - Included POD documentation at the bottom of module file.
585 - Included a VERSION comment just \*after\* the use module statements.
586 - Added the module name in alphabetical order to the @MODULES or @CURRENCY\_MODULES variable in Quote.pm.
587 - Added the module name in alphabetical order in the SEE ALSO section of the Quote.pm POD.
588 - Created a well-named test file in the t/ directory, including a test that succeeds and a test that fails. PLEASE indicate where to find valid symbols if your test file contains symbols for securities that expire such as Funds. Failing tests will cause your module to be removed from Finance::Quote if it is too difficult for maintainers to find valid symbols for tests.
589 - Ensure tests 00-store-date.t, 01-pod.t, 02-pod-coverage.t, 03-kwalitee.t, 04-critic.t, 05-data-dumper.t pass.
590 - Added module information in alphabetical order to the Modules-README.yml file.
591 - Add a quick description of the change/addition to the Changes file. Most recent changes at the top of the list. Add new lines just below the {{$NEXT}} label at the top of the file.
592
593 Contributions to Finance-Quote are best presented as pull requests on GitHub.com.
594
595 1. Create a GitHub account and sign-in
596 2. Go to https://github.com/finance-quote/finance-quote
597 3. Click "Fork" in the upper-right corner
598 4. Commit your new module and other code changes to the fork
599 5. Click "New Pull Request" on https://github.com/finance-quote/finance-quote
600 6. Click "Compare Across Forks"
601 7. Select the appropriate commits and create the merge request
602
603 Contact developers at [mailto:[email protected]](mailto:[email protected]) to discuss
604 new modules, ask questions, or get help opening a merge request.
605
606 # How to find out more
607
608 The Finance::Quote GitHub page is located at
609
610 [https://github.com/finance-quote/finance-quote](https://github.com/finance-quote/finance-quote)
611
612 and contains information about the project and links to older SourceForge
613 documentation.
614
615 # How to join the mailing lists
616
617 There are two mailing lists for Finance::Quote. These can both be accessed
618 from:
619
620 [https://sourceforge.net/p/finance-quote/mailman/](https://sourceforge.net/p/finance-quote/mailman/)