{"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>\nFrom 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>\nThe 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>\nFor 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>\nThis 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>\nThis 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