Programming performance/JasonWoof Ruby
Language: ruby
Experience level with ruby: beginner
Time taken: 50 minutes
Notes: The code is crappy for two reasons: 1) I don't know ruby very well, 2) I was racing. I spent a bunch of time looking up how to do basic things like read a line. A skilled ruby programmer could probably do this in 15 minutes.
<pre>
#!/usr/bin/ruby
$verbose = false
$bank = 10000.00
$stocks = []
file = File.new('gspc.txt')
file.readline
$last_close = file.readline.split(/[ \n]/)[6].to_f
file.each_line do |line|
words = line.split(/[ \n]/)
$close = words[6].to_f
if $verbose
print "bank: #{$bank.to_s}\n"
print "close: #{$close.to_s}\n";
print 'change: ' + ((($close - $last_close) / $last_close) * 100.0).to_s + "%\n"
end
if ($close - $last_close) / $last_close < -0.03
$stocks.push([$close, ($bank / 10) / $close])
if $verbose
print 'bought ' + (($bank / 10) / $close).to_s + " shares at #{$close}\n"
print 'bank: ' + $bank.to_s + "\n"
end
$bank *= 0.9;
end
thresh = $close / 1.06
new_stocks = [];
$stocks.each do |row|
held_close = row[0]
held_count = row[1]
if(held_close <= thresh)
$bank += held_count * $close;
if $verbose
print "sold #{held_count} shares that were bought at #{held_close.to_s}\n"
print "bank: #{$bank}\n"
end
else
new_stocks.push [held_close, held_count]
end
end
$stocks = new_stocks
$last_close = $close
end
$stocks.each do |row|
held_close = row[0]
held_count = row[1]
$bank += held_count * $close;
end
print 'bank: ' + $bank.to_s + "\n"
exit;
</pre>