Created
December 5, 2013 17:00
-
-
Save zacwasielewski/7809163 to your computer and use it in GitHub Desktop.
Command-line Perl script for viewing stock portfolio performance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use LWP::Simple; | |
%stocks = ( | |
'AAPL' => [{'q'=>100,'p'=>75.00 }], | |
'MXIM' => [{'q'=>100,'p'=>28.82 }], | |
'LLTC' => [{'q'=>200,'p'=>31.25 }], | |
'YHOO' => [{'q'=>100,'p'=>23.46 }], | |
'WU' => [{'q'=>125,'p'=>21.09 }, | |
{'q'=>125,'p'=>21.97 }] | |
); | |
sub colorize { | |
my $text = $_[0]; | |
my $color = $_[1]; | |
return chr(27)."[01;$color m$text".chr(27)."[00m"; | |
} | |
sub quote_row { | |
my $ticker = $_[0]; | |
my $qty = $_[1]; | |
my $cost = $_[2]; | |
my $quote = $_[3]; | |
$ticker = @quote[0]; | |
$price = sprintf "%.2f",@quote[1]; | |
$purchase_worth = $qty * $cost; | |
$current_worth = $qty * $price; | |
$change = sprintf "%.2f",@quote[4]; | |
$change_pct = sprintf "%.2f",@quote[5]; | |
$gain = $current_worth - $purchase_worth; | |
$current_worth = sprintf "%.2f", $current_worth; | |
$gain = sprintf "%.2f", $gain; | |
$gain_pct = sprintf "%.2f", ($gain / $current_worth) * 100; | |
$daygain = sprintf "%.2f", $qty * $change; | |
$total_daygain += $daygain; | |
$total_gain += $gain; | |
$total += $current_worth; | |
return sprintf "%-6s %8s %7s %9s %7s %6s %9s %6s %10s\n", | |
$ticker,$cost,$price,$daygain,$change,$change_pct,$gain,$gain_pct,$current_worth; | |
} | |
printf "TICKER PURCH CURR DAY +/- %% GAIN %% TOTAL\n"; | |
printf "------+--------+------- ---------+-------+------ ---------+------+----------\n"; | |
$total_daygain = 0; | |
$total_gain = 0; | |
$total = 0; | |
while (($ticker,$config) = each(%stocks)) { | |
$data = get("http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=sl1d1t1c1p2ohgv&e=.csv"); | |
die "Failed to get Stock Data" unless defined $data; | |
$data =~ s/\"//g; | |
@quote = split(/,/,$data); | |
foreach (@$config) { | |
$qty = $_->{'q'}; | |
$cost = sprintf "%.2f",$_->{'p'}; | |
print quote_row($ticker,$qty,$cost,$quote); | |
} | |
} | |
$total_gain_pct = sprintf "%.2f", ($total_gain / $total) * 100; | |
printf "------+--------+------- ---------+-------+------ ---------+------+----------\n"; | |
printf " %7.2f %9.2f %6s %10.2f\n", | |
$total_daygain,$total_gain,$total_gain_pct,$total; | |
exit 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found this in my archives dating back to September, 2007. Was I seriously still writing Perl only six years ago?!