Sunday, March 26, 2017

Handy Perl for Tax Time

Convert

1/15/15 Bought 10 MXL MAXLINEAR INC $14.38 4.95 164.2
1/2/16 Bought 60 MXL MAXLINEAR INC $14.38 4.95 724
3/2/2016 Sold -52 MXL MAXLINEAR INC $17.14 4.95 $0.03 $886.31

to

3/2/2016 MXL 70 886.31 various 888.2

You'll generate a bunch of these I hope and later put the column headings on - in Excel :

sell-date, ticker, quantity, proceeds, buy-date, cost-basis...... profit/loss easy to do in Excel..

Use :

#!/usr/bin/perl -w

open( INFO, "$source");

$cost = 0;
$sale = 0;
$qty = 0;
$buy_d = '';

while( ){
 /^\s*(\S+)\s+(\S+)\D+(\d+)\s+(\S+).+\s+\(?\$?([^\s)]+)\)?\h*\r?$/; $type = $2; $date = $1; $q = $3; $tick = $4; $total = $5; $total =~ s/,//g; if( $type =~ /bought/i ){ $qty += $q; $cost += abs( $total ); unless( 'various' eq $buy_d ){ if( '' eq $buy_d ){ $buy_d = $date; } else{ $buy_d = 'various'; } } } else { $sale += abs( $total ); $sell_d = $date;
  $sell_q = $q;
}
print; } $cost = $cost*$sell_q/$qty; print "\n$sell_d,$tick,$sell_q,$sale,$buy_d,$cost\n";

The astute reader will notice that I'm dumping a CSV line - so you could just pipe through perl -p -e 's/,/ /g;' - which will of course mess up the original - but who cares :) CSV's are more useful in Excel..

No comments: