Skip to content

Fast and Simple Stock Quotes Using Perl

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.


To start, installing Finance::Quote is a breeze. As long as you have CPAN installed, just type at the command line:

$perl -MCPAN -e shell
>install Finance::Quote

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:

#!/usr/bin/perl -w
use strict;
 
# import module
use Finance::Quote;
# create object
my $q = Finance::Quote->new();

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:

australia           Australan Stock Exchange
dwsfunds            Deutsche Bank Gruppe funds
fidelity            Fidelity Investments
tiaacref            TIAA-CREF
troweprice          T. Rowe Price
europe              European Markets
canada              Canadian Markets
usa                 USA Markets
nyse                New York Stock Exchange
nasdaq              NASDAQ
uk_unit_trusts      UK Unit Trusts
vanguard            Vanguard Investments
vwd                 Vereinigte Wirtschaftsdienste GmbH

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.
Fetch() 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.
Using this information we can now build a simple script to fetch a stock quote:

#!/usr/bin/perl -w
use strict;
 
# import module
use Finance::Quote;
 
# create object
my $q = Finance::Quote->new();
 
# retrieve stock quote
my %data = $q->fetch('usa', 'GOOG');
 
# print price
print $data{'GOOG', 'price'} . "\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:

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

This is very simple, but it does its job well:

$ quote goog msft aapl dell java
GOOGLE (GOOG)            $352.32
MICROSOFT CP (MSFT)      $22.32
APPLE INC (AAPL)         $98.23
DELL INC (DELL)          $11.99
SUN MICROSYSTEMS (JAVA)  $4.54

Download the script here

{ 1 } Comments

  1. Vishwa | April 6, 2009 at 6:19 am | Permalink

    Thanks. I will surly try it :)

Post a Comment

Your email is never published nor shared. Required fields are marked *