Class: Quant::TimePeriod

Inherits:
Object
  • Object
show all
Defined in:
lib/quant/time_period.rb

Constant Summary collapse

LOWER_BOUND =
TimeMethods::EPOCH_TIME

Instance Method Summary collapse

Constructor Details

#initialize(start_at: nil, end_at: nil, span: nil) ⇒ TimePeriod

Returns a new instance of TimePeriod.



7
8
9
10
11
12
13
14
# File 'lib/quant/time_period.rb', line 7

def initialize(start_at: nil, end_at: nil, span: nil)
  @start_at = as_start_time(start_at)
  @end_at = as_end_time(end_at)
  validate_bounds!

  @start_at = @end_at - span if !lower_bound? && span
  @end_at = @start_at + span if !upper_bound? && span
end

Instance Method Details

#==(other) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/quant/time_period.rb', line 58

def ==(other)
  return false unless other.is_a?(TimePeriod)

  if lower_bound?
    other.lower_bound? && start_at == other.start_at
  elsif upper_bound?
    oher.upper_bound? && end_at == other.end_at
  else
    [start_at, end_at] == [other.start_at, other.end_at]
  end
end

#as_end_time(value) ⇒ Object



22
23
24
25
26
# File 'lib/quant/time_period.rb', line 22

def as_end_time(value)
  return value if value.nil? || value.is_a?(Time)

  value.is_a?(Date) ? value.to_time.end_of_day : value.to_time
end

#as_start_time(value) ⇒ Object



16
17
18
19
20
# File 'lib/quant/time_period.rb', line 16

def as_start_time(value)
  return value if value.nil? || value.is_a?(Time)

  value.is_a?(Date) ? value.to_time.beginning_of_day : value.to_time
end

#cover?(value) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/quant/time_period.rb', line 34

def cover?(value)
  (start_at..end_at).cover?(value)
end

#durationObject



54
55
56
# File 'lib/quant/time_period.rb', line 54

def duration
  end_at - start_at
end

#end_atObject



50
51
52
# File 'lib/quant/time_period.rb', line 50

def end_at
  (@end_at || Time.now.utc).round
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/quant/time_period.rb', line 70

def eql?(other)
  self == other
end

#lower_bound?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/quant/time_period.rb', line 42

def lower_bound?
  !!@start_at
end

#start_atObject



38
39
40
# File 'lib/quant/time_period.rb', line 38

def start_at
  (@start_at || LOWER_BOUND).round
end

#to_hObject



74
75
76
# File 'lib/quant/time_period.rb', line 74

def to_h
  { start_at:, end_at: }
end

#upper_bound?Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/quant/time_period.rb', line 46

def upper_bound?
  !!@end_at
end

#validate_bounds!Object



28
29
30
31
32
# File 'lib/quant/time_period.rb', line 28

def validate_bounds!
  return if lower_bound? || upper_bound?

  raise "TimePeriod cannot be unbounded at start_at and end_at"
end