O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  



Options data from Yahoo
Grabs options data for a given stock symbol from Yahoo.

Contributed by:
C M
[01/10/04 | Discuss (4) | Link to this hack]

The Code

Save the following code to a file called yoption.pl:

#!/usr/bin/perl -w

#
#
#   yoption.pl
#
#   This hack will grab option data for a list of stock symbols.  
#   Prints data out to the console.
#
#   depends on:
#       wget:            utility to grab data
#       symbol.file :    a file with one stock symbol per line
#       optionData.tmp : a temp file that is used by wget
#
#   This code is free software; you can redistribute it and/or
#   modify it under the same terms as Perl itself.
#

$tmpFile = "optionData.tmp";
@lines = `cat symbol.file`;
foreach $symbol (@lines){
	chomp($symbol);
    $url ="http://finance.yahoo.com/q/op?s=";
    
    `wget -q -t 2  --output-document=$tmpFile \"$url$symbol\"`;
    @file = `cat $tmpFile`;
    $i=1;
    $optionSymbols[0] = "";#get current options info
    foreach $line ( @file ){
        chomp($line);
        #
        #   Grab all future option links
        #
        if ( $line =~ /<a href="\/q\/op\?s=(.*?)\&m=(.*?)">/ ){
            $line =~ s/^(.*?)<b>(.*?)<\/b>\s\|\s//g;
            $line =~ s/<a href="\/q\/op\?s=.*?&m=(.*?)">.*?<\/a>/$1,/g;
            $line =~ s/\||\s//g;
            (@optList) = split(",",$line);
            foreach $oi (@optList){
               $optionSymbols[$i++] = $oi;
            }
        }
    }
    for($j = 0; $j <= $#optionSymbols;$j++){
        sleep(2);# don't thrash the servers
		print "$optionSymbols[$j]\n";
        $u = $url.$symbol."&m=".$optionSymbols[$j];
        `wget -q -t 2  --output-document=$tmpFile \"$u\"`;
        @file = `cat $tmpFile`;
        $i=0;
        foreach $line ( @file ){
            chomp($line);
            if ($line =~ /^<td.*?nowrap="nowrap"><b><a href="\/q\/op\?s/ ){
                # 
                #   Clean up the lines
                #
                $line =~ s/<td.*?>//g;
                $line =~ s/<\/td>/ /g;
                $line =~ s/<a href=.*?">|<\/a>//g;
                $line =~ s/<b.*?>//g;
                $line =~ s/<\/b>/ /g;
                $line =~ s/<img.*?>//g;
                $line =~ s/\s+/ /g;
       			($symPrice,$sym,$last,$change,$bid,$ask,$vol,$openInterest) = split(" ",$line);
                print "$sym-$symPrice -> last:$last chg:$change bid:$bid ask:$ask vol:$vol o-i:$openInterest\n";
            } elsif ($line =~ /<td><small><b>PUT OPTIONS/){
                next; # skip put options
            }
        }
		print "\n";
    }
}
exit(0);


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.