Class: TimeSeries

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/time_series/time_series.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ TimeSeries

Returns a new instance of TimeSeries.



6
7
8
9
10
11
12
13
14
15
# File 'lib/time_series/time_series.rb', line 6

def initialize(*args)
  case args.length
  when 1 then data_points = args[0]
  when 2 then data_points = args[0].zip(args[1]).collect { |dp| DataPoint.new(dp[0], dp[1]) }
  else data_points = []
  end

  @data_points = {}
  self << data_points
end

Instance Attribute Details

#data_pointsObject (readonly)

Returns the value of attribute data_points.



4
5
6
# File 'lib/time_series/time_series.rb', line 4

def data_points
  @data_points
end

Instance Method Details

#<<(*data_points) ⇒ Object



17
18
19
20
21
# File 'lib/time_series/time_series.rb', line 17

def <<(*data_points)
  data_points.flatten.each do |data_point|
    @data_points[data_point.timestamp] = data_point
  end
end

#at(*timestamps) ⇒ Object



23
24
25
26
27
28
# File 'lib/time_series/time_series.rb', line 23

def at(*timestamps)
  results = @data_points.values_at(*timestamps)
  results = results[0] if results.length == 1

  return results
end

#each(&block) ⇒ Object



44
45
46
# File 'lib/time_series/time_series.rb', line 44

def each(&block)
  Hash[@data_points.sort].values.each(&block)
end

#last(n = 1) ⇒ Object



48
49
50
# File 'lib/time_series/time_series.rb', line 48

def last(n = 1)
  Hash[@data_points.sort.last(n)].values
end

#lengthObject



52
53
54
# File 'lib/time_series/time_series.rb', line 52

def length
  @data_points.length
end

#slice(timeframe) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/time_series/time_series.rb', line 30

def slice(timeframe)
  from, to = timeframe[:from], timeframe[:to]

  data_points = @data_points.select do |t, data|
    case [!from.nil?, !to.nil?]
    when [true, true] then t >= from and t <= to
    when [true, false] then t >= from
    when [false, true] then t <= to
    end
  end

  return self.class.new data_points.keys, data_points.values
end

#to_aObject



56
57
58
# File 'lib/time_series/time_series.rb', line 56

def to_a
  Hash[@data_points.sort].values
end