Class: Yfinrb::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/yfinrb/utils.rb

Constant Summary collapse

BASE_URL =
'https://query1.finance.yahoo.com'

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.loggerObject

Returns the value of attribute logger.



8
9
10
# File 'lib/yfinrb/utils.rb', line 8

def logger
  @logger
end

Class Method Details

.build_template(data) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/yfinrb/utils.rb', line 67

def self.build_template(data)
  template_ttm_order = []
  template_annual_order = []
  template_order = []
  level_detail = []

  def traverse(node, level)
    return if level > 5

    template_ttm_order << "trailing#{node['key']}"
    template_annual_order << "annual#{node['key']}"
    template_order << node['key']
    level_detail << level
    return unless node['children']

    node['children'].each { |child| traverse(child, level + 1) }
  end

  data['template'].each { |key| traverse(key, 0) }

  [template_ttm_order, template_annual_order, template_order, level_detail]
end

.camel2title(strings, sep: ' ', acronyms: nil) ⇒ Object

Raises:

  • (TypeError)


137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/yfinrb/utils.rb', line 137

def self.camel2title(strings, sep: ' ', acronyms: nil)
  raise TypeError, "camel2title() 'strings' argument must be iterable of strings" unless strings.is_a?(Enumerable)
  raise TypeError, "camel2title() 'strings' argument must be iterable of strings" unless strings.all? { |s| s.is_a?(String) }
  raise ValueError, "camel2title() 'sep' argument = '#{sep}' must be single character" unless sep.is_a?(String) && sep.length == 1
  raise ValueError, "camel2title() 'sep' argument = '#{sep}' cannot be alpha-numeric" if sep.match?(/[a-zA-Z0-9]/)
  raise ValueError, "camel2title() 'sep' argument = '#{sep}' cannot be special character" if sep != Regexp.escape(sep) && !%w[ -].include?(sep)

  if acronyms.nil?
    pat = /([a-z])([A-Z])/
    rep = '\1' + sep + '\2'
    strings.map { |s| s.gsub(pat, rep).capitalize }
  else
    raise TypeError, "camel2title() 'acronyms' argument must be iterable of strings" unless acronyms.is_a?(Enumerable)
    raise TypeError, "camel2title() 'acronyms' argument must be iterable of strings" unless acronyms.all? { |a| a.is_a?(String) }
    acronyms.each do |a|
      raise ValueError, "camel2title() 'acronyms' argument must only contain upper-case, but '#{a}' detected" unless a.match?(/^[A-Z]+$/)
    end

    pat = /([a-z])([A-Z])/
    rep = '\1' + sep + '\2'
    strings = strings.map { |s| s.gsub(pat, rep) }

    acronyms.each do |a|
      pat = /(#{a})([A-Z][a-z])/
      rep = '\1' + sep + '\2'
      strings = strings.map { |s| s.gsub(pat, rep) }
    end

    strings.map do |s|
      s.split(sep).map do |w|
        if acronyms.include?(w)
          w
        else
          w.capitalize
        end
      end.join(sep)
    end
  end
end

.empty_df(index = nil) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/yfinrb/utils.rb', line 48

def self.empty_df(index = nil)
  # index ||= []
  empty = Polars::DataFrame.new({
    'Timestamps' => DateTime.new(2000,1,1,0,0,0),
    'Open' => Float::NAN, 'High' => Float::NAN, 'Low' => Float::NAN,
    'Close' => Float::NAN, 'Adj Close' => Float::NAN, 'Volume' => Float::NAN
  })
  # empty = index.each_with_object({}) { |i, h| h[i] = empty }
  # empty['Date'] = 'Date'
  empty
end

.empty_earnings_dates_dfObject



60
61
62
63
64
65
# File 'lib/yfinrb/utils.rb', line 60

def self.empty_earnings_dates_df
  {
    'Symbol' => 'Symbol', 'Company' => 'Company', 'Earnings Date' => 'Earnings Date',
    'EPS Estimate' => 'EPS Estimate', 'Reported EPS' => 'Reported EPS', 'Surprise(%)' => 'Surprise(%)'
  }
end

.format_annual_financial_statement(level_detail, annual_dicts, annual_order, ttm_dicts = nil, ttm_order = nil) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/yfinrb/utils.rb', line 113

def self.format_annual_financial_statement(level_detail, annual_dicts, annual_order, ttm_dicts = nil, ttm_order = nil)
  annual = annual_dicts.each_with_object({}) { |d, h| h[d['index']] = d }
  annual = annual_order.each_with_object({}) { |k, h| h[k] = annual[k] }
  annual = annual.transform_keys { |k| k.gsub('annual', '') }

  if ttm_dicts && ttm_order
    ttm = ttm_dicts.each_with_object({}) { |d, h| h[d['index']] = d }
    ttm = ttm_order.each_with_object({}) { |k, h| h[k] = ttm[k] }
    ttm = ttm.transform_keys { |k| k.gsub('trailing', '') }
    statement = annual.merge(ttm)
  else
    statement = annual
  end

  statement = statement.transform_keys { |k| camel2title(k) }
  statement.transform_values { |v| v.transform_keys { |k| camel2title(k) } }
end

.format_quarterly_financial_statement(statement, level_detail, order) ⇒ Object



131
132
133
134
135
# File 'lib/yfinrb/utils.rb', line 131

def self.format_quarterly_financial_statement(statement, level_detail, order)
  statement = order.each_with_object({}) { |k, h| h[k] = statement[k] }
  statement = statement.transform_keys { |k| camel2title(k) }
  statement.transform_values { |v| v.transform_keys { |k| camel2title(k) } }
end

.get_all_by_isin(isin, proxy: nil, session: nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/yfinrb/utils.rb', line 11

def self.get_all_by_isin(isin, proxy: nil, session: nil)
  raise ArgumentError, 'Invalid ISIN number' unless is_isin(isin)

  session ||= Net::HTTP
  url = "#{BASE_URL}/v1/finance/search?q=#{isin}"
  data = session.get(URI(url), 'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept' => 'application/json')
  data = JSON.parse(data.body)
  ticker = data['quotes'][0] || {}
  {
    'ticker' => {
      'symbol' => ticker['symbol'],
      'shortname' => ticker['shortname'],
      'longname' => ticker['longname'],
      'type' => ticker['quoteType'],
      'exchange' => ticker['exchDisp']
    },
    'news' => data['news'] || []
  }
rescue StandardError
  {}
end

.get_info_by_isin(isin, proxy: nil, session: nil) ⇒ Object



38
39
40
41
# File 'lib/yfinrb/utils.rb', line 38

def self.get_info_by_isin(isin, proxy: nil, session: nil)
  data = get_all_by_isin(isin, proxy: proxy, session: session)
  data['ticker'] || {}
end

.get_news_by_isin(isin, proxy: nil, session: nil) ⇒ Object



43
44
45
46
# File 'lib/yfinrb/utils.rb', line 43

def self.get_news_by_isin(isin, proxy: nil, session: nil)
  data = get_all_by_isin(isin, proxy: proxy, session: session)
  data['news'] || {}
end

.get_ticker_by_isin(isin, proxy: nil, session: nil) ⇒ Object



33
34
35
36
# File 'lib/yfinrb/utils.rb', line 33

def self.get_ticker_by_isin(isin, proxy: nil, session: nil)
  data = get_all_by_isin(isin, proxy: proxy, session: session)
  data.dig('ticker', 'symbol') || ''
end

.interval_to_timedelta(interval) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/yfinrb/utils.rb', line 261

def self.interval_to_timedelta(interval)
  case interval
  when '1mo'
    1.month
  when '2mo'
    2.months
  when '3mo'
    3.months
  when '6mo'
    6.months
  when '9mo'
    9.months
  when '12mo'
    1.year
  when '1y'
    1.year
  when '2y'
    2.year
  when '3y'
    3.year
  when '4y'
    4.year
  when '5y'
    5.year
  when '1wk'
    1.week
  when '2wk'
    2.week
  when '3wk'
    3.week
  when '4wk'
    4.week
  else
    Rails.logger.warn { "#{__FILE__}:#{__LINE__} #{interval} not a recognized interval" }
    interval
  end
end

.is_isin(string) ⇒ Object

data end



244
245
246
# File 'lib/yfinrb/utils.rb', line 244

def self.is_isin(string)
  /^[A-Z]{2}[A-Z0-9]{9}[0-9]$/.match?(string)
end

.parse_user_dt(dt, exchange_tz) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/yfinrb/utils.rb', line 248

def self.parse_user_dt(dt, exchange_tz)
  if dt.is_a?(Integer)
    Time.at(dt)
  elsif dt.is_a?(String)
    dt = DateTime.strptime(dt.to_s, '%Y-%m-%d') 
  elsif dt.is_a?(Date)
    dt = dt.to_datetime 
  elsif dt.is_a?(DateTime) && dt.zone.nil?
    dt = dt.in_time_zone(exchange_tz)
  end
  dt.to_i
end

.retrieve_financial_details(data) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/yfinrb/utils.rb', line 90

def self.retrieve_financial_details(data)
  ttm_dicts = []
  annual_dicts = []

  data['timeSeries'].each do |key, timeseries|
    next unless timeseries

    time_series_dict = { 'index' => key }
    timeseries.each do |each|
      next unless each

      time_series_dict[each['asOfDate']] = each['reportedValue']
    end
    if key.include?('trailing')
      ttm_dicts << time_series_dict
    elsif key.include?('annual')
      annual_dicts << time_series_dict
    end
  end

  [ttm_dicts, annual_dicts]
end

.snake_case_2_camelCase(s) ⇒ Object



177
178
179
# File 'lib/yfinrb/utils.rb', line 177

def self.snake_case_2_camelCase(s)
  s.split('_').first + s.split('_')[1..].map(&:capitalize).join
end

Instance Method Details

#traverse(node, level) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/yfinrb/utils.rb', line 73

def traverse(node, level)
  return if level > 5

  template_ttm_order << "trailing#{node['key']}"
  template_annual_order << "annual#{node['key']}"
  template_order << node['key']
  level_detail << level
  return unless node['children']

  node['children'].each { |child| traverse(child, level + 1) }
end