Perl : Using the Finance::Quote module to get your stock prices
stephane
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 ๐