{"id":21,"date":"2008-10-23T22:18:05","date_gmt":"2008-10-24T06:18:05","guid":{"rendered":"http:\/\/sethjust.wordpress.com\/?p=21"},"modified":"2010-12-23T16:38:59","modified_gmt":"2010-12-24T00:38:59","slug":"fast-and-simple-stock-quotes-using-perl","status":"publish","type":"post","link":"https:\/\/sethjust.com\/2008\/10\/23\/fast-and-simple-stock-quotes-using-perl\/","title":{"rendered":"Fast and Simple Stock Quotes Using Perl"},"content":{"rendered":"

One of the things that makes perl so powerful and fascinating is the huge number of modules that are available online, especially through the CPAN repository. Today I stumbled upon one called Finance::Quote, which does one thing, very simply: it retrieves stock (or mutual fund) quotes. You feed it a ticker symbol and it gives back a hash with all sorts of information, but most importantly, the price. I’m going to show how to use this to create a command line tool that will grab an up-to-the minute stock quote for any ticker symbol you give it.<\/p>\n


\nTo start, installing Finance::Quote is a breeze. As long as you have CPAN installed, just type at the command line:<\/p>\n

$perl -MCPAN -e shell\r\n>install Finance::Quote<\/pre>\n

From there it’s easy to get start, it’s just a matter of importing the module and creating and instance. This means the beginning of our script will look like:<\/p>\n

#!\/usr\/bin\/perl -w\r\nuse strict;\r\n\r\n# import module\r\nuse Finance::Quote;\r\n# create object\r\nmy $q = Finance::Quote->new();<\/pre>\n

The instance that we created has one main method: fetch(). It takes a list of arguments, with the first being a the exchange to look for quotes on, and the remaining being a list or array of ticker symbols. The Finance::Quote documentation provides the following list of valid exchanges:<\/p>\n

australia           Australan Stock Exchange\r\ndwsfunds            Deutsche Bank Gruppe funds\r\nfidelity            Fidelity Investments\r\ntiaacref            TIAA-CREF\r\ntroweprice          T. Rowe Price\r\neurope              European Markets\r\ncanada              Canadian Markets\r\nusa                 USA Markets\r\nnyse                New York Stock Exchange\r\nnasdaq              NASDAQ\r\nuk_unit_trusts      UK Unit Trusts\r\nvanguard            Vanguard Investments\r\nvwd                 Vereinigte Wirtschaftsdienste GmbH<\/pre>\n

For the purposes of this script, I’m going to stick to “usa” because it covers both NYSE and NASDAQ, and those are the stocks I’m interested in.
\nFetch() returns a two-dimensional hash of results. The first index (or dimension) is the ticker symbol of the stock and the second is the label for the specific piece of information. For now, the labels that we’re interested are the name of the company (‘name’) and the price (‘price’). A full listing of labels is available in the Finance::Quote documentation.
\nUsing this information we can now build a simple script to fetch a stock quote:<\/p>\n

#!\/usr\/bin\/perl -w\r\nuse strict;\r\n\r\n# import module\r\nuse Finance::Quote;\r\n\r\n# create object\r\nmy $q = Finance::Quote->new();\r\n\r\n# retrieve stock quote\r\nmy %data = $q->fetch('usa', 'GOOG');\r\n\r\n# print price\r\nprint $data{'GOOG', 'price'} . \"\\n\";<\/pre>\n

This script, although it does what it’s supposed to, isn’t very pretty. By adding a little code to read ticker symbols from the command line we can check on multiple stocks at the same time, as well as remove the need to hard-code the ticker symbols. We can also make it produce much prettier results by adding more information about the company and add some basic error checking, which yields the following script:<\/p>\n

#!\/usr\/bin\/perl -w\r\nuse strict;\r\n\r\n# import module\r\nuse Finance::Quote;\r\n\r\n# create object\r\nmy $q = Finance::Quote->new();\r\n\r\n#print usage information\r\nif (length(@ARGV) == 0) {\r\n\tprint \"Usage: $0 ticker1, ticker2, ... , tickerN\\n\";\r\n\texit;\r\n}\r\n\r\n# get stock symbols from the command line and\r\n# format them correctly (uppercase)\r\nfor (@ARGV){\r\n\t$_ = uc();\r\n}\r\n\r\n# retrieve stock quote\r\nmy %data = $q->fetch('usa', @ARGV);\r\n\r\n# print result for each stock\r\nfor (@ARGV){\r\n\tif ($data{$_, 'success'}) {\t\t# if getting the quote succeeded\r\n\t\tmy $name = $data{$_, 'name'};\t# build a report\r\n\t\tmy $price = $data{$_, 'price'};\r\n\t\tmy $message = '';\r\n\t\t$message .= $name . ' (' . $_ . ')';\r\n\t\t$message .= ' ' x(25 - length($message));\r\n\t\t$message .= \"$$price\\n\";\r\n\t\tprint $message;\r\n\t}\r\n\telse { print \"Failed to retrieve quote for $_: $data{$_, 'errormsg'}\\n\"; }\r\n}<\/pre>\n

This is very simple, but it does its job well:<\/p>\n

$ quote goog msft aapl dell java\r\nGOOGLE (GOOG)            $352.32\r\nMICROSOFT CP (MSFT)      $22.32\r\nAPPLE INC (AAPL)         $98.23\r\nDELL INC (DELL)          $11.99\r\nSUN MICROSYSTEMS (JAVA)  $4.54<\/pre>\n

Download the script here<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"

One of the things that makes perl so powerful and fascinating is the huge number of modules that are available online, especially through the CPAN repository. Today I stumbled upon one called Finance::Quote, which does one thing, very simply: it retrieves stock (or mutual fund) quotes. You feed it a ticker symbol and it gives […]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4,6,7],"tags":[28,29,30,37,40,156,77,84,88,90],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/posts\/21"}],"collection":[{"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/comments?post=21"}],"version-history":[{"count":7,"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/posts\/21\/revisions"}],"predecessor-version":[{"id":219,"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/posts\/21\/revisions\/219"}],"wp:attachment":[{"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/media?parent=21"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/categories?post=21"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sethjust.com\/wp-json\/wp\/v2\/tags?post=21"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}