Class: StockCruncher::InfluxDB

Inherits:
Object
  • Object
show all
Defined in:
lib/stockcruncher/influxdb.rb

Overview

this is a class to write time series to database

Instance Method Summary collapse

Constructor Details

#initialize(config, insecure = false) ⇒ InfluxDB

Class constructor method



11
12
13
14
# File 'lib/stockcruncher/influxdb.rb', line 11

def initialize(config, insecure = false)
  @cfg = config[self.class.name.split('::').last]
  @insecure = insecure
end

Instance Method Details

#export_history(symbol, timeseries) ⇒ Object

Method to export historical data to database



24
25
26
27
28
29
# File 'lib/stockcruncher/influxdb.rb', line 24

def export_history(symbol, timeseries)
  tags = { 'symbol' => symbol }
  timeseries.each_pair do |date, values|
    write('daily', tags, values, date)
  end
end

#export_last_day(values) ⇒ Object

Method to export latest data to database



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

def export_last_day(values)
  tags = { 'symbol' => values.delete('symbol') }
  date = values.delete('latestDay')
  write('daily', tags, values, date)
end

#format_values(values) ⇒ Object

Method to format and array of values into comma separated string



32
33
34
35
36
37
38
39
# File 'lib/stockcruncher/influxdb.rb', line 32

def format_values(values)
  string = ''
  values.each_pair do |k, v|
    string += "#{k}=#{v}"
    string += ',' unless k == values.keys.last
  end
  string
end

#request(url, body) ⇒ Object

Method to send http post request



42
43
44
45
46
47
48
49
50
51
# File 'lib/stockcruncher/influxdb.rb', line 42

def request(url, body)
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme.eql?('https')
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @insecure
  req = Net::HTTP::Post.new(uri.request_uri)
  req.basic_auth(@cfg['user'], @cfg['password'])
  req.body = body
  http.request(req)
end

#write(name, tags, values, date) ⇒ Object

Method to write data in bucket



54
55
56
57
58
59
60
61
# File 'lib/stockcruncher/influxdb.rb', line 54

def write(name, tags, values, date)
  url = "#{@cfg['scheme']}://#{@cfg['host']}:#{@cfg['port']}/write?" \
        "db=#{@cfg['dbname']}"
  timestamp = DateTime.parse(date + 'T18:00:00').strftime('%s%N')
  body = "#{name},#{format_values(tags)} #{format_values(values)} " \
         "#{timestamp}"
  request(url, body)
end