Class: YfAsDataframe::Utils
- Inherits:
-
Object
- Object
- YfAsDataframe::Utils
- Defined in:
- lib/yf_as_dataframe/utils.rb
Constant Summary collapse
- BASE_URL =
'https://query1.finance.yahoo.com'
Class Attribute Summary collapse
-
.logger ⇒ Object
Returns the value of attribute logger.
Class Method Summary collapse
- .build_template(data) ⇒ Object
- .camel2title(strings, sep: ' ', acronyms: nil) ⇒ Object
- .empty_df(index = nil) ⇒ Object
- .empty_earnings_dates_df ⇒ Object
- .format_annual_financial_statement(level_detail, annual_dicts, annual_order, ttm_dicts = nil, ttm_order = nil) ⇒ Object
- .format_quarterly_financial_statement(statement, level_detail, order) ⇒ Object
- .get_all_by_isin(isin, proxy: nil, session: nil) ⇒ Object
- .get_info_by_isin(isin, proxy: nil, session: nil) ⇒ Object
- .get_news_by_isin(isin, proxy: nil, session: nil) ⇒ Object
- .get_ticker_by_isin(isin, proxy: nil, session: nil) ⇒ Object
- .interval_to_timedelta(interval) ⇒ Object
-
.is_isin(string) ⇒ Object
data end.
- .parse_user_dt(dt, exchange_tz) ⇒ Object
- .retrieve_financial_details(data) ⇒ Object
- .snake_case_2_camelCase(s) ⇒ Object
Instance Method Summary collapse
Class Attribute Details
.logger ⇒ Object
Returns the value of attribute logger.
8 9 10 |
# File 'lib/yf_as_dataframe/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/yf_as_dataframe/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
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/yf_as_dataframe/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/yf_as_dataframe/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_df ⇒ Object
60 61 62 63 64 65 |
# File 'lib/yf_as_dataframe/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/yf_as_dataframe/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/yf_as_dataframe/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/yf_as_dataframe/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/yf_as_dataframe/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/yf_as_dataframe/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/yf_as_dataframe/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
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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
# File 'lib/yf_as_dataframe/utils.rb', line 265 def self.interval_to_timedelta(interval) case interval when '1mo' # Calculate 1 month from now to get accurate days now = Time.now next_month = Time.new(now.year, now.month + 1, now.day) # Handle year rollover next_month = Time.new(now.year + 1, 1, now.day) if next_month.month == 1 (next_month - now).to_i when '2mo' # Calculate 2 months from now now = Time.now next_month = Time.new(now.year, now.month + 2, now.day) # Handle year rollover next_month = Time.new(now.year + 1, next_month.month, now.day) if next_month.month <= 2 (next_month - now).to_i when '3mo' # Calculate 3 months from now now = Time.now next_month = Time.new(now.year, now.month + 3, now.day) # Handle year rollover next_month = Time.new(now.year + 1, next_month.month, now.day) if next_month.month <= 3 (next_month - now).to_i when '6mo' # Calculate 6 months from now now = Time.now next_month = Time.new(now.year, now.month + 6, now.day) # Handle year rollover next_month = Time.new(now.year + 1, next_month.month, now.day) if next_month.month <= 6 (next_month - now).to_i when '9mo' # Calculate 9 months from now now = Time.now next_month = Time.new(now.year, now.month + 9, now.day) # Handle year rollover next_month = Time.new(now.year + 1, next_month.month, now.day) if next_month.month <= 9 (next_month - now).to_i when '12mo' # Calculate 12 months (1 year) from now now = Time.now next_year = Time.new(now.year + 1, now.month, now.day) (next_year - now).to_i when '1y' # Calculate 1 year from now now = Time.now next_year = Time.new(now.year + 1, now.month, now.day) (next_year - now).to_i when '2y' # Calculate 2 years from now now = Time.now next_year = Time.new(now.year + 2, now.month, now.day) (next_year - now).to_i when '3y' # Calculate 3 years from now now = Time.now next_year = Time.new(now.year + 3, now.month, now.day) (next_year - now).to_i when '4y' # Calculate 4 years from now now = Time.now next_year = Time.new(now.year + 4, now.month, now.day) (next_year - now).to_i when '5y' # Calculate 5 years from now now = Time.now next_year = Time.new(now.year + 5, now.month, now.day) (next_year - now).to_i when '1wk' 7.days when '2wk' 14.days when '3wk' 21.days when '4wk' 28.days else # Logger.new(STDOUT).warn { "#{__FILE__}:#{__LINE__} #{interval} not a recognized interval" } interval end end |
.is_isin(string) ⇒ Object
data end
244 245 246 |
# File 'lib/yf_as_dataframe/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 260 261 262 263 |
# File 'lib/yf_as_dataframe/utils.rb', line 248 def self.parse_user_dt(dt, exchange_tz) if dt.is_a?(Integer) return 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 end # If it's a DateTime, convert to Time if dt.is_a?(DateTime) # If zone is nil, try to set it, else just convert dt = dt.in_time_zone(exchange_tz) if dt.zone.nil? && dt.respond_to?(:in_time_zone) dt = dt.to_time 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/yf_as_dataframe/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/yf_as_dataframe/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/yf_as_dataframe/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 |