[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Stock Quotes



This is a functional hack-job.  It uses LWP::Simple to lookup a stock
quote from Yahoo's stocks.  Scrapes through the page to try and pull out
stock information.  If yahoo changes page format, this'll probably break.

But here we go:
> stock YHOO
YHOO currently at 402 3/4 (+12 1/2 change)
> stock quote MSFT
MSFT currently at 117 3/4 (+1/4 change)
> stock price of LNUX
LNUX currently at 178 (-5 change)
> stock for RHAT
RHAT currently at 224 1/4 (-7 3/4 change)

The regex is pretty flexible...

Jay
# 
#  Stock -- infobot module for stock quote lookups.
# 	    requires the LWP::Simple module.
#  By Jay Jacobs (teckle)
#

package Infobot::Module::Stock;

use strict;
use Infobot::Module;

$Infobot::Module::Stock::VERSION = "0.01_00";
$Infobot::Module{"Stock"} = $Infobot::Module::Stock::VERSION;
@Infobot::Module::Stock::ISA = qw(Infobot::Module);

my $any_bad;

BEGIN {
  eval { require LWP::Simple };
  $@ and $any_bad = "LWP::Simple";
  warn "Infobot::Module::Stock requires $any_bad" if $any_bad;
}

sub Infobot::Module::Stock::new {
  my $class = shift ;
  return undef if $any_bad;

  my $self  = $class->SUPER::new(@_);
  $self->weight(0); 
  
  $self->enabled(1);
  $self->name('Stock');
  $self->regex(qr/stock\s+(?:price |quote |for )?\s*(?:for|at|of)?\s*(\S+)/i);
  $self->usage('stock <SYMBOL>');
  $self->descrip("Tries to lookup stock quote for SYMBOL");

  bless $self, $class;
}

sub Infobot::Module::Stock::action {
  my ($self, $message) = @_;
  return undef unless $self->enabled;

  my $symbol = uc($message->get('args')->[0]);
  $self->status(2,"looking up stock for $symbol");
  my $content = LWP::Simple::get("http://finance.yahoo.com/q?s=$symbol\&d=v1");
  return("$symbol: could not get information") if (! defined $content);
  my $found = 0;
  my @goods;
  foreach (split(/\n/, $content)) {
    next unless (($found) || ((/border\s*=\s*1/) && (/<table/i)));
    last if (/<\/table>/i);
    $found=1;
    (s/<[^>]+>//g);
    push (@goods, $_) if (/\w+/);
  }
  return ("$symbol: not valid, try looking up symbols at http://finance.yahoo.com/l") if ($goods[$#goods]=~/Try\s+Symbol\s+Lookup/i);
  return ("$goods[5] currently at $goods[7] ($goods[8] change)");
}

1;

__END__

=head1 NAME

Stock -- looks up the current stock quote of a given stock.

=head1 SYNOPSIS

stock for <SYMBOL>

stock quote for <SYMBOL>

=head1 PREREQUISITES

	LWP::Simple

=head1 DESCRIPTION

	Connects up to yahoo's stock webpage, does some 
	simple screen-scraping, and returns what it can.  Which
	means that it could very easily be broken if Yahoo changes
	their webpage format.

=head1 AUTHORS

Jay Jacobs (teckle) <jjacobs@securetty.org>