Reputation: 73
I'm trying to sort specific data from my Broker to a format that i can paste into GoogleSheets (which then does some calculations for logging it in a Journal). Being new to ruby (less than 20 hrs experience) so excuse any bad formatting or logical errors.
Able to get 95% of required output, just want to Sort it based on 'Date' column.
Result- https://i.sstatic.net/T5lQz.png
Input File - https://www.dropbox.com/s/xhtr6cda95c2i7f/AI.txt?dl=0
Any help would be appreciated. Thanks
AllItems = Array.new()
#filename="AI.txt"
def read_transcations(filename)
lines=open(filename)
transaction = Array.new
lines.each do |record| transaction.push(record) end
transaction.each do |value| output=value.split("|")
AllItems.push(output)
end
puts
return AllItems
end #end of main function
def main
answer = read_transcations("AI.txt")
t_tradeType = 0, t_orderID = 1, t_ticker = 2, t_ticker_description = 3, t_exchange = 4,
t_action = 5, t_action_tag = 6, t_date = 7, t_time = 8, t_currency = 9, t_quantity = 10,
t_unknown = 11, t_price = 12, t_total = 13, t_comission = 14, t_unknown2 = 15
i=0 ;t_count=(answer.length-1)
puts "There are total #{t_count} transactions."
puts "Date\t\t Ticker\tIn \t\tOut \tTime_in\t\tTime_out\tComission\n\
------------------------------------------------------------------------"
t_count.times do |x|
if answer[x][t_ticker] == answer[x+1][t_ticker]
#Buy/Sell/Quantity
buy=answer[x][t_price].to_f ; sell=answer[i+1][t_price].to_f ; qty=answer[x][t_quantity].to_f
#Comission
comm = (((answer[x][t_comission]).to_f)+(((answer[x+1][t_comission]).to_f))).abs
#Profit/Loss
gain = (((sell-buy)*qty)-comm).round(2)
if answer[x][t_action] == "SELLTOPEN"
gain = gain-(gain*2)
end
#Time In and Time Out
require 'time'
t_in = Time.parse(answer[x][t_time]) ; t_out = Time.parse(answer[x+1][t_time])
time_diff=((t_out-t_in)/60.to_i).round(2)
#Date
require 'date'
p_date = Date.parse(answer[x][t_date])
#OutPut for GoogleSheets
puts "#{p_date} \t#{answer[x][t_ticker]} \t#{buy.round(3)} \t#{sell.round(3)} \t#{answer[x][t_time]} \t#{answer[x+1][t_time]} \t#{comm.round(2)}"
#Interactive Standard output
#puts "#{x+1}. Ticker #{answer[x][t_ticker]} -> Date = #{answer[x][t_date]}, Comm = #{comm.round(2)} Duration = #{time_diff} Min, P/L = $#{gain},"
end
i=i+1;
end
end #End of main
main
Upvotes: 0
Views: 182
Reputation: 73
Adding the following
AllItems.sort!{|x,y| x[7] <=> y[7]}
after Line 10 solved the problem. Thanks a lot.
Upvotes: 0
Reputation: 1157
Sortintg multi-dimensional array - that is array of arrays - in Ruby is no different than sorting array of any other object.
a.sort { |x,y| y[5] <=> x[5] }
or
a.sort! { |x,y| y[5] <=> x[5] }
where 5 is index o your date column.
Upvotes: 1