Skip to content

Instantly share code, notes, and snippets.

@yrral86
Created May 9, 2013 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yrral86/5551203 to your computer and use it in GitHub Desktop.
Save yrral86/5551203 to your computer and use it in GitHub Desktop.
Calculates maximum spread price. Assumes trades.csv is in the following format timestamp1,price timestamp2,price etc. additional fields will not cause problems, but if the timestamp and price are not in those positions, you can adjust the indices on the line with Trade.new the seconds variable will set the maximum time span to examine
gem 'active_support'
gem 'algorithms'
require 'algorithms'
require 'active_support/core_ext/module'
# trade class
class Trade
attr_accessor :price, :time
def initialize(price, time)
@price = price
@time = time
end
end
# monkey patch heap
class Containers::Heap
def set_max_seconds(n)
@max_seconds = n
end
def push_with_time(key, value=key)
@max_time = 0 if @max_time.nil?
@max_time = value.time if value.time > @max_time
push_without_time(key, value)
end
alias_method_chain :push, :time
def next_with_time
pop while next_without_time.time + @max_seconds < @max_time
next_without_time
end
alias_method_chain :next, :time
end
# one hour
seconds = 60*60
max_heap = Containers::MaxHeap.new
max_heap.set_max_seconds(seconds)
min_heap = Containers::MinHeap.new
min_heap.set_max_seconds(seconds)
max_spread = 0
trades = open("trades.csv", "r").read.split("\n")
trades.each do |trade|
data = trade.split(',')
# Trade.new(price, time)
t = Trade.new(data[1].to_i, data[0].to_i)
min_heap.push(t.price, t)
max_heap.push(t.price, t)
spread = max_heap.next.price - min_heap.next.price
max_spread = spread if spread > max_spread
end
puts "Maximum spread within #{seconds} seconds: $#{max_spread}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment