Generate start and end values from time series
This commit is contained in:
parent
a05bb6c2f6
commit
19a161a79b
@ -1,5 +1,6 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'csv'
|
||||
require 'json'
|
||||
require 'net/http'
|
||||
require 'net/https'
|
||||
@ -10,7 +11,20 @@ class CPIFetcher
|
||||
resp = fetch_raw_response
|
||||
return nil unless resp['Results']['series']
|
||||
|
||||
latest_cpi_value(resp['Results']['series'].first['data'])
|
||||
data = resp['Results']['series'].first['data']
|
||||
{
|
||||
start: start_cpi_value(data),
|
||||
latest: latest_cpi_value(data)
|
||||
}
|
||||
end
|
||||
|
||||
def cpi_csv
|
||||
values = cpi
|
||||
CSV.generate do |csv|
|
||||
csv << ['year', 'value']
|
||||
csv << [start_year, values.fetch(:start)]
|
||||
csv << [end_year, values.fetch(:latest)]
|
||||
end
|
||||
end
|
||||
|
||||
private def url
|
||||
@ -22,7 +36,7 @@ class CPIFetcher
|
||||
|
||||
private def series_id
|
||||
@series_id ||= ENV.fetch(
|
||||
'CPI_SERIES_ID', 'CUURS000SA0,CUUSS000SA0'
|
||||
'CPI_SERIES_ID', 'CUUR0200SA0'
|
||||
).split(/[, ]/).map(&:strip).reject(&:empty?)
|
||||
end
|
||||
|
||||
@ -38,6 +52,17 @@ class CPIFetcher
|
||||
@bls_token ||= ENV.fetch('BLS_TOKEN')
|
||||
end
|
||||
|
||||
private def start_cpi_value(data)
|
||||
data = data.sort do |a, b|
|
||||
record_key(a) <=> record_key(b)
|
||||
end
|
||||
data.first.fetch('value')
|
||||
end
|
||||
|
||||
private def record_key(record)
|
||||
"#{record['year']}.#{record['period']}"
|
||||
end
|
||||
|
||||
private def latest_cpi_value(data)
|
||||
data.find { |d| d['latest'] == 'true' }.fetch('value')
|
||||
end
|
||||
@ -66,6 +91,6 @@ class CPIFetcher
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
puts CPIFetcher.new.cpi
|
||||
puts CPIFetcher.new.cpi_csv
|
||||
exit 0
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user