1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-08-03 04:25:21 +02:00
Maybe/app/models/time_series.rb

58 lines
1.2 KiB
Ruby
Raw Normal View History

class TimeSeries
2024-04-18 20:03:46 -06:00
DIRECTIONS = %w[ up down ].freeze
2024-04-18 20:03:46 -06:00
attr_reader :values, :favorable_direction
2024-04-18 20:03:46 -06:00
def self.from_collection(collection, value_method)
collection.map do |obj|
{
date: obj.date,
value: obj.public_send(value_method),
original: obj
}
end.then { |data| new(data) }
2024-04-18 18:03:52 -06:00
end
2024-04-18 20:03:46 -06:00
def initialize(data, favorable_direction: "up")
@favorable_direction = (favorable_direction.presence_in(DIRECTIONS) || "up").inquiry
@values = initialize_values data
2024-04-18 18:03:52 -06:00
end
2024-04-18 18:03:52 -06:00
def first
values.first
end
2024-04-18 18:03:52 -06:00
def last
values.last
end
2024-04-18 18:03:52 -06:00
def on(date)
values.find { |v| v.date == date }
end
2024-04-18 18:03:52 -06:00
def trend
2024-04-18 20:03:46 -06:00
TimeSeries::Trend.new \
2024-04-18 18:03:52 -06:00
current: last&.value,
previous: first&.value,
2024-04-18 20:03:46 -06:00
series: self
2024-04-18 18:03:52 -06:00
end
2024-04-18 20:40:00 -06:00
# `as_json` returns the data shape used by D3 charts
def as_json
2024-04-18 18:03:52 -06:00
{
2024-04-18 20:03:46 -06:00
values: values.map(&:as_json),
trend: trend.as_json,
2024-04-19 19:35:34 -06:00
favorableDirection: favorable_direction
2024-04-18 20:40:00 -06:00
}.as_json
2024-04-18 18:03:52 -06:00
end
2024-04-18 18:03:52 -06:00
private
2024-04-18 20:03:46 -06:00
def initialize_values(data)
[ nil, *data ].each_cons(2).map do |previous, current|
TimeSeries::Value.new **current,
previous_value: previous.try(:[], :value),
2024-04-18 20:03:46 -06:00
series: self
2024-04-18 18:03:52 -06:00
end
end
end