er (1567B)
1 #!/usr/bin/awk -f 2 # Written 2024-03-13 3 # 4 # Has two functions: 5 # 1. Calculate the expense of each asset in a list using it's 6 # expense ratio 7 # 2. Calculate the weighted expense ratio for each asset given 8 # 9 # Expense ratios are listed in a file with 10 # symbol er 11 # on each line specifying the expense ratio for symbol. 12 # 13 # Assets are listed in a format like so 14 # symbol value 15 # where value is a number defining the value of the asset (which 16 # may be USD) 17 18 function die(msg) 19 { 20 status = 1 21 print "error: " msg > "/dev/stderr" 22 exit status 23 } 24 25 function load_ers(file, _s) 26 { 27 while (_s = getline < file) 28 ers[$1] = $2; 29 return _s != 0 30 } 31 32 function er(symbol) 33 { 34 if (!(symbol in ers)) 35 die(symbol ": Expense ratio not defined"); 36 return ers[symbol]; 37 } 38 39 BEGIN { 40 FS = " " 41 OFS = FS 42 OFMT = "%.2f" 43 44 if (!ARGV[1]) 45 die("No expense-ratios"); 46 if (load_ers(ARGV[1])) 47 die("Unable to load ERs: I/O error"); 48 delete ARGV[1]; 49 50 if (ARGV[2] ~ /^-/) { 51 action = substr(ARGV[2], 2) 52 delete ARGV[2] 53 } 54 } 55 56 { 57 if (!NF || !/^ *[^#]/) { 58 print 59 next 60 } 61 62 if (!action || action == "costs") { 63 print $1, $2 * (er($1) / 100) 64 } else if (action == "weighted") { 65 amounts[$1] += $2; 66 total += $2; 67 } else 68 die("Invalid action"); 69 } 70 71 END { 72 if (status) 73 exit status 74 75 if (action != "weighted") 76 exit 77 78 OFMT = "%.3f" 79 for (symbol in amounts) { 80 percent = amounts[symbol] / (total / 100) 81 weighted = (percent * er(symbol)) / 100 82 comment = sprintf("%.2f%% ER, %5.2f%% of funds valued at %.2f", 83 er(symbol), percent, amounts[symbol]); 84 print symbol, weighted, comment 85 } 86 }