Generate start and end values from time series

This commit is contained in:
Dan Buch 2020-01-09 20:07:54 -05:00
parent a05bb6c2f6
commit 19a161a79b
Signed by: meatballhat
GPG Key ID: 9685130D8B763EA7

View File

@ -1,5 +1,6 @@
# frozen_string_literal: true # frozen_string_literal: true
require 'csv'
require 'json' require 'json'
require 'net/http' require 'net/http'
require 'net/https' require 'net/https'
@ -10,7 +11,20 @@ class CPIFetcher
resp = fetch_raw_response resp = fetch_raw_response
return nil unless resp['Results']['series'] 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 end
private def url private def url
@ -22,7 +36,7 @@ class CPIFetcher
private def series_id private def series_id
@series_id ||= ENV.fetch( @series_id ||= ENV.fetch(
'CPI_SERIES_ID', 'CUURS000SA0,CUUSS000SA0' 'CPI_SERIES_ID', 'CUUR0200SA0'
).split(/[, ]/).map(&:strip).reject(&:empty?) ).split(/[, ]/).map(&:strip).reject(&:empty?)
end end
@ -38,6 +52,17 @@ class CPIFetcher
@bls_token ||= ENV.fetch('BLS_TOKEN') @bls_token ||= ENV.fetch('BLS_TOKEN')
end 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) private def latest_cpi_value(data)
data.find { |d| d['latest'] == 'true' }.fetch('value') data.find { |d| d['latest'] == 'true' }.fetch('value')
end end
@ -66,6 +91,6 @@ class CPIFetcher
end end
if $PROGRAM_NAME == __FILE__ if $PROGRAM_NAME == __FILE__
puts CPIFetcher.new.cpi puts CPIFetcher.new.cpi_csv
exit 0 exit 0
end end