#!perl
use warnings;
use strict;
use diagnostics;
use Getopt::Long;
use Date::Manip;
use DBI;
use HTML::TreeBuilder;
use Text::CSV_XS;
use LWP::Simple qw/get/;
# TODO: Write out LaTeX report
sub recall {
my $DATE_FORMAT = \'%Y-%m-%d\';
my $GOOGLE_DATE_FORMAT = \'%b+%d,+%Y\';
my $infilename = UnixDate(\'today\', $DATE_FORMAT).".csv";
my $outfilename = UnixDate(\'today\', $DATE_FORMAT)."_recall.csv";
open(my $out, \'>\', "$outfilename") or die "$!\\n";
# http://finance.google.com/finance/historical?output=csv&q=bXXXXXX&startdate=Jan+01,+2007&enddate=Aug+14,+2015&
my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1, eol => "$/" });
open my $fh, "<:encoding(utf8)", "$infilename" or die "$infilename: $!";
open my $out, ">:encoding(utf8)", "outfilename" or die "$outfilename: $!";
$csv->print($out, [\'Stock Symbol\',\'Change\']);
while (my $row = $csv->getline ($fh)) {
next unless $row->[0] =~ /^[A-Z]+$/;
my $stock = $row->[0];
my $startdate = UnixDate(\'yesterday\',$GOOGLE_DATE_FORMAT);
my $enddate = UnixDate(\'today\', $GOOGLE_DATE_FORMAT);
my $googleUrl = "http://finance.google.com/finance/historical?output=csv&q=$stock&startdate=$startdate&enddate=$enddate";
my @data = split /,/, get($googleUrl);
my $change = $data[14]-$data[9];
$csv->print($out, [$stock, $change]);
$csv->print(\\*STDERR, [$stock, $change]);
}
close $fh;
close($outfilename);
}
sub precision {
my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1, eol => "$/" });
my $DATE_FORMAT = \'%Y-%m-%d\';
my $today = UnixDate(\'now\', $DATE_FORMAT);
open (my $out, \'>\', "$today.csv") or die "$!\\n";
my $URL = \'http://madmoney.thestreet.com/screener/index.cfm?showview=stocks&showrows=500\';
my $tree = HTML::TreeBuilder->new_from_url($URL);
my $stockTable = $tree->look_down(\'_tag\',\'table\', sub { $_[0]->{\'id\'} eq \'stockTable\'; });
my @stocks = [];
my @s = $stockTable->look_down(\'_tag\',\'td\', sub { $_[0]->as_text =~ /\\(([^)]+)\\)/ && push @stocks, "$1";});
my @direction = [];
my @d = $stockTable->look_down(\'_tag\', \'img\', sub { $_[0]->{\'src\'} =~ /([1-5])\\.gif/ && push @direction, "$1"; });
$csv->print($out, [\'stock\', "Cramer\'s predicted direction"]);
$csv->eol;
my $stocks = $#d;
for (my $i = 0; $i < $stocks; $i++) {
$csv->print($out, [$stocks[$i], "down"]) if $direction[$i] eq \'1\';
$csv->print($out, [$stocks[$i], \'up\']) if $direction[$i] eq \'5\';
$csv->eol if $stocks[$i];
}
close($out);
$tree->delete;
}
my $operation;
GetOptions("op=s", \\$operation) or die("Error in command line arguments\\n");
&precision if $operation eq \'get\';
&recall if $operation eq \'check\';