Debian Codegraph @

lib/Finance/Quote/USBonds.pm

raw
1 #!/usr/bin/perl -w
2 # vi: set ts=2 sw=2 expandtab noai ic showmode showmatch:
3 #
4 # USBonds.pm
5 # A GNUCash quote source that uses the treasurydirect.gov website to obtain
6 # current prices for U.S. Treasury bonds, such as E, EE, I, etc.
7 # The user provides the necessary specifications for their bonds and this
8 # routine queries the website for the prices.
9 #
10 # Kenneth J. Farley
11 # 2018-02-03
12 #
13 # This program is free software; you can redistribute it and/or modify it
14 # under the terms of the GNU General Public License as published by the
15 # Free Software Foundation; either version 2 of the License, or (at your
16 # option) any later version.
17 #
18 # This program is distributed in the hope that it will be useful, but WITHOUT
19 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
20 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License along with
23 # this program; if not, write the Free Software Foundation, Inc., 59 Temple
24 # Place - Suite 330, Boston, MA 02111-1307, USA.
25 #
26
27 package Finance::Quote::USBonds ;
28 require 5.010 ;
29
30 use strict ;
31 use warnings ;
32
33 use LWP::UserAgent ;
34 use HTTP::Request::Common ;
35 use HTML::TreeBuilder ;
36
37 use constant DEBUG => $ENV{DEBUG};
38 use if DEBUG, 'Smart::Comments', '###';
39
40 our $VERSION = '1.71'; # VERSION
41
42 #
43 # Define constants.
44 #
45
46 our $DISPLAY = 'USBonds - US Treasury Bonds';
47 our @LABELS = qw/exchange method source symbol currency date isodate version price/;
48 our $METHODHASH = {subroutine => \&usbonds,
49 display => $DISPLAY,
50 labels => \@LABELS};
51
52 sub methodinfo {
53 return (
54 usbonds => $METHODHASH,
55 );
56 }
57
58 # --- [ labels ] --------------------------------------------------------------
59 #
60 # This method also seems to be a requirement of a Finance::Quote module, but
61 # there doesn't seem to be any documentation of what it is supposed to include,
62 # or why.
63 #
64
65 sub labels {
66 my %m = methodinfo();
67 return map {$_ => [@{$m{$_}{labels}}] } keys %m;
68 }
69
70 # --- [ methods ] -------------------------------------------------------------
71 #
72 # A Finance::Quote module must have a methods() subroutine, which is called by
73 # when it loads the module. It's used to determine which methods the module
74 # provides. Thus, though there are a number of subroutines defined, only those
75 # we want to make 'public' are included here.
76 #
77
78 sub methods {
79 my %m = methodinfo();
80 return map {$_ => $m{$_}{subroutine} } keys %m;
81 }
82
83 my $urlBonds = "https://www.treasurydirect.gov/BC/SBCPrice" ;
84
85 #
86 # Package variables, necessary to allow the different subroutines to access the
87 # same data.
88 #
89
90 my %quotes ;
91 my ( @listDenomination, @listSeries, @listIssueDate, @listDateNums ) ;
92 my ( @listQuoteDate, @listPrices, @validSymbols ) ;
93
94 # --- [ getTodaysDate ] -------------------------------------------------------
95 #
96 # Returns a string that contains today's date in the format 'YYYY-MM-DD'. It uses
97 # the 'localtime' function, adjusting and formatting the data appropriately.
98 #
99
100 sub getTodaysDate
101 {
102 my $useIsoFormat = $_[0] ;
103 if ( defined $useIsoFormat )
104 {
105 $useIsoFormat = ( $useIsoFormat > 0 ) ;
106 }
107 else
108 {
109 $useIsoFormat = ( 0 == 1 ) ;
110 }
111 my ( $s, $m, $h, $dayToday, $monthToday, $yearToday, $w, $y, $i ) = localtime ;
112 $monthToday += 1 ;
113 $yearToday += 1900 ;
114 if ( $useIsoFormat )
115 {
116 $yearToday . '-' . $monthToday . '-' . $dayToday ;
117 }
118 else
119 {
120 $monthToday . '/' . $dayToday . '/' . $yearToday ;
121 }
122 }
123
124 # --- [ isDateValid ] ---------------------------------------------------------
125 #
126 # Savings bonds, like any government organization, have a confusing melange of
127 # valid issue dates, depending upon the series and denomination. This routine
128 # will determine, given a set of parameters, whether the bond described is
129 # valid.
130 #
131 # The algorithm, if it can be dignified with that title, calculates an integer
132 # date value which is 12 times the year added to the month. The number is used
133 # to compare the date to the acceptable range of dates for the given bond
134 # series.
135 #
136 # Usage: isDateValid ( denom, series, month, year )
137 #
138 # Arguments
139 # denom : the monetary denomination, in USD.
140 # series : the series of the bond.
141 # month : an integer from 1 (January) to 12 (December).
142 # year : a four digit integer representing the year.
143 #
144 # Returns a boolean value indicating if the given combination of parameters
145 # describes a valid bond.
146 #
147
148 sub isDateValid
149 {
150 my $denom = $_[0] ;
151 my $series = $_[1] ;
152 my $datenum = $_[2] + 12 * $_[3] ;
153 my $result = ( 0 == 1 ) ;
154
155 if ( $series eq 'E' )
156 {
157 $result = ( $datenum > 4 + 1941 * 12 && $datenum < 7 + 1980 * 12 ) ;
158 if ( $result && $denom == 10 )
159 {
160 $result = ( $datenum > 5 + 1944 * 12 && $datenum < 4 + 1950 * 12 ) ;
161 }
162 if ( $result && $denom == 75 )
163 { $result = ( $result && $datenum > 4 + 1964 * 12 ) ; }
164 if ( $result && $denom == 200 )
165 { $result = ( $result && $datenum > 9 + 1945 * 12 ) ; }
166 if ( $result && $denom == 10000 )
167 { $result = ( $result && $datenum > 4 + 1952 * 12 ) ; }
168 }
169
170 #
171 # Series I
172 # Issue Dates 1998-09 to 2009-08
173 # Denominations : 200 and 10000
174 #
175 if ( $series eq 'I' )
176 {
177 $result = ( $datenum > 8 + 1998 * 12 && $datenum < 9 + 2009 * 12 ) ;
178 if ( $result && $denom == 200 )
179 { $result = ( $result && $datenum > 4 + 1999 * 12 ) ; }
180 if ( $result && $denom == 10000 )
181 {
182 $result = ( $datenum > 4 + 1999 * 12 && $datenum < 12 + 2007 * 12 ) ;
183 }
184 }
185
186 #
187 # Series EE
188 # Issue Dates 1980-01 to present
189 # Denominations : 50, 75, 100, 200, 500, 1000, 2000, 5000, and 10000
190 #
191 if ( $series eq 'EE' )
192 {
193 $result = ( $denom =~ /10{2,4}|50{1,3}|75|20{2,3}/ ) ;
194 $result = ( $result && $datenum > 12 + 1979 * 12 ) ;
195 }
196 $result ;
197 }
198
199 # --- [ buildForm ] -----------------------------------------------------------
200 #
201 # Builds a form that is to be 'posted' to the website that provides pricing
202 # data for bonds. The form contains the minimum data necessary to get data
203 # from the site. Note that some of the data series stored in the form are just
204 # blank placeholders.
205 #
206 # Arguments
207 # listDen : a reference to an array of the monetary denomination, in USD.
208 # listSer : a reference to an array the series of the bond.
209 # listDat : a reference to an array of issue dates
210 #
211 # Returns a form populated with the data provided in the lists.
212 #
213
214 sub buildForm
215 {
216 my ( $yr, $mo ) = ( &getTodaysDate ( 1 ) =~ m/([0-9]+)\-([0-9]+)\-[0-9]+/ ) ;
217 my @listDen = @{ $_[0] } ;
218 my @listSer = @{ $_[1] } ;
219 my @listDat = @{ $_[2] } ;
220 my %result =
221 (
222 SerialNumList => ' ;' x ( scalar @listDen ),
223 RedemptionDate => $mo . "/" . $yr,
224 IssueDateList => join ( ';', @listDat ) . ';',
225 SeriesList => join ( ';', @listSer ) . ';',
226 DenominationList => join ( ';', @listDen ) . ';',
227 IssuePriceList => ' ;' x ( scalar @listDen ),
228 InterestList => ' ;' x ( scalar @listDen ),
229 YTDInterestList => ' ;' x ( scalar @listDen ),
230 ValueList => ' ;' x ( scalar @listDen ),
231 InterestRateList => ' ;' x ( scalar @listDen ),
232 NextAccrualDateList => ' ;' x ( scalar @listDen ),
233 MaturityDateList => ' ;' x ( scalar @listDen ),
234 NoteList => ' ;' x ( scalar @listDen ),
235 OldRedemptionDate => ' ;' x ( scalar @listDen ),
236 ViewPos => '1',
237 ViewType => 'Partial',
238 Version => '6',
239 'btnUpdate.x' => 'UPDATE',
240 ) ;
241 }
242
243 # --- [ parseSymbol ] ---------------------------------------------------------
244 #
245 # Parses a provided symbol, determines if it is valid, and if so, adds its data
246 # to the global arrays of information and the global validSymbols list.
247 #
248 # The valid symbol pattern is
249 #
250 # SS-DDD-YYYY-MM
251 #
252 # Where
253 # SS = series I, E, or EE
254 # DDD = denomination 50, 75, 100, 200, 500, 1000 5000 or 10000
255 # YYYY = year of issuance
256 # MM = month of issuance
257 #
258 # Symbols parsed are checked for validity according to the above rules, and
259 # return a hopefully helpful indication of what is wrong, whether it be the
260 # overall format, or the individual tokens of the symbol.
261 #
262
263 sub parseSymbol
264 {
265 my $symbol = uc $_[0] ;
266 my $regexpSymbol = "^([A-Za-z]{1,2})-(\\d{2,5})-(\\d{4})-(\\d{2})" ;
267 my ( $ser, $den, $yr, $mo ) = ( $symbol =~ m/$regexpSymbol/ ) ;
268 my $okFormat = ( $den && $ser && $yr && $mo ) ;
269 my $errorMsg = "" ;
270 my $okTokens = ( 1 == 1 ) ;
271 if ( $okFormat )
272 {
273 my $okDenom = ( $den =~ /10{1,4}|50{1,3}|25|75|200/ ) ;
274 my $okSeries = ( $ser =~ /E{1,2}|I/ ) ;
275 my $okYear = ( $yr =~ /194[1-9]|19[5-9]\d|20\d{2}/ ) ;
276 my $okMonth = ( $mo =~ /0[1-9]|1[0-2]/ ) ;
277 if ( $okSeries && $okDenom )
278 {
279 if ( $ser eq 'I' || $ser eq 'EE' )
280 { $okDenom = ( $den > 26 ) ; }
281 if ( $ser eq 'E' )
282 { $okDenom = ( $den != 5000 ) ; }
283 }
284 my $okDate = &isDateValid ( $den, $ser, $mo, $yr ) ;
285 my $okTokens = ( $okDenom && $okSeries && $okYear && $okMonth && $okDate) ;
286 if ( $okTokens )
287 {
288 push @listDenomination, $den ;
289 push @listSeries, $ser ;
290 push @listIssueDate, $mo . "/" . $yr ;
291 push @listDateNums, ( $yr * 12 + $mo - 23296 ) ;
292 push @validSymbols, $symbol ;
293 }
294 else
295 {
296 $errorMsg = "Symbol \"" . $symbol . "\" Bad tokens:\n" ;
297 if ( ! $okDenom )
298 { $errorMsg .= " denomination \"" . $den . "\"" ; }
299 if ( ! $okSeries )
300 { $errorMsg .= " series \"" . $ser . "\"" ; }
301 if ( ! $okYear )
302 { $errorMsg .= " year \"" . $yr . "\"" ; }
303 if ( ! $okMonth )
304 { $errorMsg .= " month \"" . $mo . "\"" ; }
305 if ( ! $okDate )
306 { $errorMsg .= " date \"" . $yr . "-" . $mo . "\"" ; }
307 }
308 }
309 else
310 {
311 $errorMsg = "Symbol \"" . $symbol . "\" incorrect format" ;
312 }
313 $quotes { $symbol, "success" } = $okFormat && $okTokens ;
314 unless ( $okFormat && $okTokens )
315 {
316 $quotes { $symbol, "errormsg" } = $errorMsg ;
317 $quotes { $symbol, "success" } = 0;
318 }
319 }
320
321 # --- [ getQuoteDates ] ----------------------------------------------------
322 #
323 # Interest is accrued for some bonds every 6 months, and for others monthly.
324 # The treasurydirect bond pricing calculator provides a 'next accrual date'
325 # field for each bond.
326 # This routine traverses the list of valid bonds and finds the latest accrual
327 # date that has passed. By doing so, when the pricing information is provided
328 # to GnuCash, it will not generate duplicate quotes, even if this module is
329 # used multiple times in the same month.
330 #
331 # The algorithm used is as follows:
332 # (1) Get the date today from the 'getTodaysDate' function.
333 # (2) Starting last month, get the next accrual date for all the bonds.
334 # (3) For any accrual dates that are less than or equal to this month, record
335 # them in the appropriate list.
336 # (4) Go to the next month back, and get the next accrual date for any bonds
337 # that have not got any yet.
338 # (5) Continue to the next month back for any bonds that aren't matched, etc.
339 #
340 # All the quote dates are saved as the first day of the month, or '01/MM/YYYY'
341 # and an isodate of 'YYYY-MM-01'.
342 #
343
344 sub getQuoteDates
345 {
346 my ( $yr, $mo ) = ( &getTodaysDate ( 1 ) =~ m/([0-9]+)\-([0-9]+)\-[0-9]+/ ) ;
347 my $dateNumToday = $yr * 12 + $mo - 23296 ;
348 @listQuoteDate = split ';', ( '-;' x ( scalar @validSymbols ) ) ;
349 my $userAgent = LWP::UserAgent->new ;
350
351 my $moNext = $mo ;
352 my $yrNext = $yr ;
353 for ( my $deltaMonth = 1 ; $deltaMonth <= 6 ; $deltaMonth++ )
354 {
355 $moNext-- ;
356 if ( $moNext < 1 )
357 {
358 $moNext += 12 ;
359 $yrNext -= 1 ;
360 }
361 my $countItems = 0 ;
362 my ( @listDat, @listDen, @listSer ) ;
363 for ( my $index = 0 ; $index < ( scalar @validSymbols ) ; $index++ )
364 {
365 if ( $listQuoteDate [ $index ] eq "-" )
366 {
367 push @listDat, $listDateNums [ $index ] ;
368 push @listDen, $listDenomination [ $index ] ;
369 push @listSer, $listSeries [ $index ] ;
370 $countItems++ ;
371 }
372 }
373 if ( $countItems > 0 )
374 {
375 my %formQuery = &buildForm ( \@listDen, \@listSer, \@listDat ) ;
376 $formQuery{ 'RedemptionDate' } = $moNext . '/' . $yrNext ;
377 my $resData = $userAgent->post ( $urlBonds, \%formQuery ) ;
378 if ( $resData->is_success )
379 {
380 my $treeQuery = HTML::TreeBuilder->new_from_content ( $resData->content ) ;
381 $treeQuery->elementify () ;
382 my $valueQuery =
383 (
384 $treeQuery->look_down
385 (
386 sub
387 {
388 $_[0]->tag() eq 'input'
389 and $_[0]->attr ( 'type' ) eq 'hidden'
390 and $_[0]->attr ( 'name' ) eq 'NextAccrualDateList'
391 }
392 )
393 ) ;
394 if ( defined ( $valueQuery ) )
395 {
396 my @listNext = split ";", $valueQuery->{value} ;
397 my $indexRes = 0 ;
398 for ( my $indexDate = 0 ; $indexDate < ( scalar @validSymbols ) ; $indexDate++ )
399 {
400 if ( $listQuoteDate [ $indexDate ] eq "-" )
401 {
402 my $dateNum = $listNext [ $indexRes ] ;
403 if ( $dateNum <= $dateNumToday )
404 {
405 my $yr = int ( ( $listNext [ $indexRes ] + 23296 ) / 12 ) ;
406 my $mo = ( $listNext [ $indexRes ] + 23296 ) % 12 ;
407 if ( $mo < 1 )
408 {
409 $mo += 12 ;
410 $yr -= 1 ;
411 }
412 if ( $mo < 10 ) { $mo = '0' . $mo ; }
413 $listQuoteDate [ $indexDate ] = $mo . '/' . $yr ;
414 }
415 $indexRes++ ;
416 }
417 }
418 }
419 }
420 }
421 }
422 } # getQuoteDates
423
424 # --- [ getQuotes ] -----------------------------------------------------------
425 #
426 # Uses the lists that have been built pertaining to the bonds, to get the
427 # current prices by posting a form with the data to the treasurydirect website.
428 # The prices are extracted from the resulting data using HTML::TreeBuilder.
429 #
430
431 sub getQuotes
432 {
433 my %formBonds = &buildForm ( \@listDenomination, \@listSeries, \@listIssueDate ) ;
434 my $userAgent = LWP::UserAgent->new ;
435 my $resData = $userAgent->post ( $urlBonds, \%formBonds ) ;
436 if ( $resData->is_success )
437 {
438 my $treeBonds = HTML::TreeBuilder->new_from_content ( $resData->content ) ;
439 $treeBonds->elementify () ;
440 my $valueBonds =
441 ( $treeBonds->look_down
442 ( sub
443 {
444 $_[0]->tag() eq 'input' and
445 $_[0]->attr ( 'type' ) eq 'hidden' and
446 $_[0]->attr ( 'name' ) eq 'ValueList'
447 }
448 )
449 ) ;
450 if ( defined ( $valueBonds ) )
451 {
452 $valueBonds->{value} =~ s/;$// ;
453 @listPrices = split ';', $valueBonds->{value} ;
454 }
455 }
456 } # end getQuotes
457
458 # --- [ usbonds ] -------------------------------------------------------------
459 #
460 # The main routine, which is the option that will be selected within GnuCash to
461 # get prices for bonds.
462 #
463 # The algorithm used is as follows:
464 #
465 # (1) Parse the symbol to determine the series, face value, issue date, etc.
466 # (2) For the valid symbols that result from the parsing, get quotes.
467 # (3) Build the hash table by adding all the valid symbols with their pertin-
468 # ent data.
469 # (4) Return the hash table.
470 #
471 # Arguments
472 # quoter : string that identifies the module. This argument is ignored.
473 # symbol1 : 1st symbol
474 # symbol2 : 2nd symbol
475 # .
476 # .
477 # .
478 # symboln : nth symbol
479 #
480
481 sub usbonds
482 {
483 my $quoter = shift ;
484 my @symbols = @_ ;
485
486 return unless @symbols ;
487
488 foreach my $symbol ( @symbols )
489 {
490 &parseSymbol ( $symbol ) ;
491 }
492
493 if ( scalar @validSymbols > 0 )
494 {
495 &getQuotes ;
496 &getQuoteDates ;
497
498 ### listPrices: @listPrices
499
500 for ( my $index = 0 ; $index < scalar @validSymbols ; $index++ ) {
501 my $keyNow = $validSymbols [ $index ] ;
502 if ( defined $listPrices [ $index ] ) {
503 my ( $mo, $yr ) = ( $listQuoteDate [ $index ] =~ m/([0-9]+)\/([0-9]+)/ ) ;
504 $quotes { $keyNow, "exchange" } = "Treasury Direct" ;
505 $quotes { $keyNow, "method" } = "usbonds" ;
506 $quotes { $keyNow, "price" } = $listPrices [ $index ] ;
507 $quotes { $keyNow, "last" } = $listPrices [ $index ] ;
508 $quotes { $keyNow, "symbol" } = $validSymbols [ $index ] ;
509 $quotes { $keyNow, "currency" } = "USD" ;
510 $quotes { $keyNow, "source" } = "USBonds" ;
511 $quotes { $keyNow, "date" } = $mo . "/01/" . $yr ;
512 $quotes { $keyNow, "isodate" } = $yr . "-" . $mo . "-01" ;
513 $quotes { $keyNow, "version" } = '1.10' ;
514 $quotes { $keyNow, "success" } = 1 ;
515 } else {
516 $quotes { $keyNow, "success" } = 0;
517 $quotes { $keyNow, "errormsg" } = "No price data for $keyNow";
518 }
519 }
520 }
521 return wantarray() ? %quotes : \%quotes;
522 }
523
524 1 ;
525
526 =head1 NAME
527
528 Finance::Quote::USBonds - Obtain quotes for US Federal Bonds in the E, EE, or I series
529 from the Treasury Direct website, http://www.treasurydirect.gov.
530
531 =head1 SYNOPSIS
532
533 use Finance::Quote ;
534
535 $q = Finance::Quote->new ;
536
537 %quote = $q->fetch ( "usbonds", "\EE-100-1993-10" ) ;
538
539 =head1 DESCRIPTION
540
541 Module obtains quote information from the Treasury Direct website, www.treasurydirect.gov.
542 Given a bond symbol, obtains the current prices for it.
543
544 The symbol nomenclature is as follows:
545
546 SS-DDDDD-YYYY-MM
547
548 Where
549 SS = series (EE, E, or I)
550 DDDDD = denomination
551 YYYY = year issued
552 MM = month issued
553
554 For example, 'EE-500-1988-02'
555
556 The symbols supplied are checked for format and validity. For example, bonds
557 were only issued after 1942, only the specific denominations issued for EE
558 bonds are allowed, etc.
559
560 =head1 LABELS RETURNED
561
562 The following labels may be returned by Finance::Quote::USBonds:
563 exchange method source symbol currency date isodate version price
564
565 =head1 SEE ALSO
566
567 Treasury bond value web interface - http://www.treasurydirect.gov/BC/SBCPrice
568
569 Finance::Quote
570
571 =head1 AUTHOR
572
573 Kenneth J. Farley
574
575 =cut