Perl : Using the Finance::Quote module to get your stock prices

Finance::Quote is a Perl module which can be used to obtain stock information from various internet sources. I thought I’d rather share this code snippet as an example showing how easy it is to use, before I turn it into a bloatware with an SQL backend to compute average price per share and what not 🙂

So here is a simple snippet demonstrating how to get the price of a stock :

#! /usr/bin/perl

use strict;
use warnings;
use Finance::Quote;

my $q = Finance::Quote->new();

my @tickers = ("CS.PA", "DEXB.PA", "AF.PA", "VIE.PA", "KEYYO.PA");
my $s = $q->fetch("yahoo_europe", @tickers);

my $stocks;

while (my ($k, $v) = each %$s) {
	my $stock;
	my $label;

	($stock, $label) = (split $;, $k)[0, 1];
	$stocks->{$stock}->{$label} = $v;
}

my @data = ();
foreach (@tickers) {
	if (not $stocks->{$_}->{success}) {
		push @data, { name => $_, price => "N/A"};
	} else {
		push @data, $stocks->{$_};
	}
}
my @sorted = sort { $a->{name} cmp $b->{name} } @data;
@data = undef;

print sprintf "% -20s %s\n", "STOCK", "PRICE";
foreach (@sorted) {
	print sprintf "% -20s % 7.2f\n", $_->{name}, $_->{price};
}

The execution will provide something like that :

kattoo@roadrunner ~/bin $ ./get-stocks.pl 
STOCK                PRICE
AIR FRANCE - KLM       11.35
AXA                    16.64
DEXIA                   4.87
KEYYO                   3.30
VEOLIA ENVIRONN.       22.70
kattoo@roadrunner ~/bin $

That’s pretty simple so I won’t go into more details (feel free to ask if you need clarifications).

I’ve already added it into my conky layout with an execpi directive, and it works like a charm 🙂

One thought on “Perl : Using the Finance::Quote module to get your stock prices”

  1. I am trying to fetch quotes from a terminal following is the shown data in excel . What could be the server name , topic to use from below data

    =RTD(“now.scriprtd”,,”MktWatch”,”nse_fo|NIFTY12JANFUT”,”Trading Symbol”)

    Thanks,
    Rajesh

Comments are closed.