class SignalTools::StockData

Constants

Extra_Days

Extra days needed to produce accurate data for the desired date.

Indexes

Attributes

dates[R]
raw_data[R]

Public Class Methods

new(ticker, from_date, to_date) click to toggle source

Downloads historical prices using the YahooFinance gem.

# File lib/signal_tools/stock_data.rb, line 20
def initialize(ticker, from_date, to_date)
  @from_date = from_date
  @raw_data = YahooFinance::get_historical_quotes(ticker, @from_date-Extra_Days, to_date).reverse
  convert_raw_data_strings!
  # We will never have need of the extraneous dates so we trim here
  @dates = trim_dates
end

Public Instance Methods

close_prices() click to toggle source
# File lib/signal_tools/stock_data.rb, line 40
def close_prices
  @close_prices ||= @raw_data.map { |d| d[Indexes[:close]] }
end
high_prices() click to toggle source
# File lib/signal_tools/stock_data.rb, line 32
def high_prices
  @high_prices ||= @raw_data.map { |d| d[Indexes[:high]] }
end
low_prices() click to toggle source
# File lib/signal_tools/stock_data.rb, line 36
def low_prices
  @low_prices ||= @raw_data.map { |d| d[Indexes[:low]] }
end
open_prices() click to toggle source
# File lib/signal_tools/stock_data.rb, line 28
def open_prices
  @open_prices ||= @raw_data.map { |d| d[Indexes[:open]] }
end

Private Instance Methods

binary_search_for_date_index(dates, low=0, high=dates.size-1) click to toggle source

Performs a binary search for @from_date on @dates. Returns the index of @from_date.

# File lib/signal_tools/stock_data.rb, line 63
def binary_search_for_date_index(dates, low=0, high=dates.size-1)
  return low if high <= low    # closest match
  mid = low + (high - low) / 2
  if dates[mid] > @from_date
    binary_search_for_date_index(dates, low, mid-1)
  elsif dates[mid] < @from_date
    binary_search_for_date_index(dates, mid+1, high)
  else
    mid
  end
end
convert_raw_data_strings!(*indexes) click to toggle source
# File lib/signal_tools/stock_data.rb, line 46
def convert_raw_data_strings!(*indexes)
  @raw_data.each do |datum|
    datum[Indexes[:date]] = Date.parse(datum[Indexes[:date]])
    datum[Indexes[:open]] = datum[Indexes[:open]].to_f
    datum[Indexes[:high]] = datum[Indexes[:high]].to_f
    datum[Indexes[:low]] = datum[Indexes[:low]].to_f
    datum[Indexes[:close]] = datum[Indexes[:close]].to_f
  end
end
trim_dates() click to toggle source
# File lib/signal_tools/stock_data.rb, line 56
def trim_dates
  dates = @raw_data.map { |d| d[Indexes[:date]] }
  index = binary_search_for_date_index(dates)
  dates[(index+1)..-1]
end