Created
January 22, 2018 08:34
-
-
Save PrimeTimeTran/d90ed7d6065c4b1141c72eeed1c1df3b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class Price < ApplicationRecord | |
module Scopes | |
def daily | |
created_at.to_date.to_s(:db) | |
end | |
def weekly | |
where('created_at >= ?', 1.week.ago) | |
end | |
def weekly_highs | |
weekly_prices.map { |_, v| v.max_by(&:price) } | |
end | |
def weekly_lows | |
weekly_prices.map { |_, v| v.min_by(&:price) } | |
end | |
def weekly_prices | |
weekly.group_by { |x| x.created_at.strftime('%Y-%m-%d') } | |
end | |
def create_candlestick(group) | |
{ | |
date: group[0], | |
open: opening_price(group[1]), | |
close: closing_price(group[1]), | |
low: lowest_price(group[1]), | |
high: highest_price(group[1]) | |
} | |
end | |
def opening_price(group) | |
group.inject { |memo, price| memo.created_at < price.created_at ? memo : price }.price | |
end | |
def closing_price(group) | |
group.inject { |memo, price| memo.created_at > price.created_at ? memo : price }.price | |
end | |
def highest_price(group) | |
group.collect(&:price).max | |
end | |
def lowest_price(group) | |
group.collect(&:price).min | |
end | |
def five_minute_prices | |
time = Time.zone.now.end_of_day | |
first_price = Price.first.created_at | |
prices = {} | |
while first_price < time | |
earlier_time = time - 300 | |
later_time = time | |
prices[time] = [] | |
r = Range.new(earlier_time, later_time) | |
Price.all.each { |price| prices[time] << price if r.cover?(price.created_at) } | |
time -= 300 | |
end | |
prices.reject { |_, value| value.empty? } | |
end | |
def candlestick_data | |
prices = five_minute_prices.map do |group| | |
create_candlestick(group) | |
end | |
prices.reverse | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment