Friday, May 11, 2007

[Perl] Script to check stock

Script to check the stock and their graph :D
Uses finance.yahoo.com to get the graphs.

INPUT : stock.conf : contains stock symbol (one per line ) for each company.
You can find the symbols on http://finance.yahoo.com/lookup, if you don't know.

OUTPUT: Generates a html page that contains the information and graph for the given companies in stock.conf.

Requires: lynx
Usages: Put stocks.cgi and stock.conf in your cgi-bin directory. Open in firefox. Refresh to get latest info.
Note: you can also run the script from shell prompt and then redirect the output to a html file , then open this file in firefox :D But you need to run it every time you want the latest info.
# perl stock.cgi > mystocks.html
# firefox mystocks.html

Here are the files:

----- stocks.cgi ---
#!/usr/bin/perl -w
use strict;
use CGI qw(:standard);
#Written by Vaibhav Gupta
################ Variables ######################
my $stockfile = "stock.conf";
my $tab_width = 3;
################################################

sub generatestockhtml () {
my @allfile = `cat $stockfile `;
my $toprint = "<table frame=box><tr>\n";
my $count=0;

foreach my $line (@allfile) {
chomp $line;
my ($firstchar) = ($line =~ /(.)/ );
my $stock=`lynx -source " http://finance.yahoo.com/d/quotes.csv?s=$line&amp;f=l1d1t1c6ohgn&e=.csv"` ;
my ($lasttrade,$lasttradedate,$lasttradetime,$change,$open,$dayhigh,$daylow,$name) = split(/,/,$stock);
#Not Printing lasttradetime
$toprint .="<td>
<b>$name</b> Trade Date = $lasttradedate <br>
Current: <font color=green>$lasttrade</font> Change:<font color=red> $change</font> <br>
Open: <font color=green>$open</font> High: <font color=green>$dayhigh</font> Low: <font color=green>$daylow</font>
<a href=\" http://ichart.yahoo.com/v?s=$line\">
<img src=\"http://chart.yahoo.com/c/0b/$firstchar/$line.gif\">
</a> <br>
<a href=\"http://finance.yahoo.com/q?s=$line&d=b\"> More Info</a>
</td>
\n";
$count++;
if($count % $tab_width == 0) {
$toprint .= "</tr><tr>";
}
}
$toprint .= "</tr></table>";
print $toprint;
}


print header("text/html"),
start_html("Vaibhav Gupta's Stock Page");
my $cur = CGI->new() ;
&generatestockhtml();
print end_html;

--- stock.conf --
goog
yhoo
msft
amzn
emc