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



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

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

Instance Method Details

#create_tags(symbol) ⇒ Object

Method to create tags hash containing only symbol



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

def create_tags(symbol)
  { 'symbol' => symbol }
end

#export_history(symbol, timeseries, catchup) ⇒ Object

Method to export historical data to database



49
50
51
52
53
54
55
56
57
58
# File 'lib/stockcruncher/influxdb.rb', line 49

def export_history(symbol, timeseries, catchup)
  tags = create_tags(symbol)
  if catchup
    series = get_daily_values(symbol, true)
    series['time'].each { |date| timeseries.delete(date) }
  end
  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



61
62
63
64
65
# File 'lib/stockcruncher/influxdb.rb', line 61

def export_last_day(values)
  tags = create_tags(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



68
69
70
# File 'lib/stockcruncher/influxdb.rb', line 68

def format_values(values)
  values.map { |k, v| "#{k}=#{v}" }.join(',')
end

#get_daily_values(symbol, fullsize) ⇒ Object



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

def get_daily_values(symbol, fullsize)
  values = %w[close change changePercent volume]
  data = query('daily', symbol, values, fullsize)
  data['columns'].zip(data['values'].transpose).to_h
end

#get_ma_values(symbol, fullsize) ⇒ Object



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

def get_ma_values(symbol, fullsize)
  values = %w[ema200]
  data = query('ema', symbol, values, fullsize)
  data['columns'].zip(data['values'].transpose).to_h
end

#moving_averages(symbol, fullsize, catchup) ⇒ Object

Method to calculate moving averages based on last day values



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

def moving_averages(symbol, fullsize, catchup)
  data = get_daily_values(symbol, fullsize)
  mas = catchup ? get_ma_values(symbol, fullsize) : { 'time' => [] }
  tags = create_tags(symbol)
  dates, series, weights = data.values_at 'time', 'close', 'volume'
  series.each_index do |i|
    next if mas['time'].include? dates[i]

    write_moving_averages(tags, series[i, 201], weights[i, 201], dates[i])
    break unless fullsize
  end
end

#query(name, symbol, values, full) ⇒ Object

Method to query data in bucket

Raises:

  • (StandardError)


81
82
83
84
85
86
87
88
89
90
91
# File 'lib/stockcruncher/influxdb.rb', line 81

def query(name, symbol, values, full)
  url = "#{@cfg['scheme']}://#{@cfg['host']}:#{@cfg['port']}/query?" \
        "db=#{@cfg['dbname']}"
  size = full ? '' : 'LIMIT 201'
  body = "q=SELECT #{values.join(',')} FROM #{name} " \
         "WHERE symbol = '#{symbol}' ORDER BY time DESC #{size}"
  data = JSON.parse(request(url, body).body)['results'][0]['series']
  raise StandardError, 'No data' if data.nil?

  data[0]
end

#request(url, body) ⇒ Object

Method to send http post request



94
95
96
97
98
99
100
101
102
103
# File 'lib/stockcruncher/influxdb.rb', line 94

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



106
107
108
109
110
111
112
113
# File 'lib/stockcruncher/influxdb.rb', line 106

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

#write_moving_averages(tags, serie, weights, date) ⇒ Object

Method to calculate all statistics



73
74
75
76
77
78
# File 'lib/stockcruncher/influxdb.rb', line 73

def write_moving_averages(tags, serie, weights, date)
  write('ema', tags, StockCruncher::Stats.list_ema(serie), date)
  write('lwma', tags, StockCruncher::Stats.list_lwma(serie), date)
  write('sma', tags, StockCruncher::Stats.list_sma(serie), date)
  write('vwma', tags, StockCruncher::Stats.list_vwma(serie, weights), date)
end