Module: Yfinrb::PriceHistory

Extended by:
ActiveSupport::Concern
Includes:
ActionView::Helpers::NumberHelper
Included in:
Ticker
Defined in:
lib/yfinrb/price_history.rb

Constant Summary collapse

PRICE_COLNAMES =
['Open', 'High', 'Low', 'Close', 'Adj Close']
BASE_URL =
'https://query2.finance.yahoo.com'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

attr_accessor :ticker



14
15
16
17
18
19
20
21
22
# File 'lib/yfinrb/price_history.rb', line 14

def self.included(base) # built-in Ruby hook for modules
  base.class_eval do
    original_method = instance_method(:initialize)
    define_method(:initialize) do |*args, &block|
      original_method.bind(self).call(*args, &block)
      initialize_price_history # (your module code here)
    end
  end
end

Instance Method Details

#actionsObject



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/yfinrb/price_history.rb', line 255

def actions
  history(period: "max") if @history.nil?

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} @history = #{@history.inspect}" }
  if !@history.nil? #&& @history.columns.include?("Dividends") && @history.columns.include?("Stock Splits")
    # action_columns = ["Dividends", "Stock Splits"]

    # action_columns.append("Capital Gains") if @history.columns.include?("Capital Gains")

    # actions = @history[action_columns]
    # return actions[actions != 0].dropna(how: 'all').fillna(0)
    df = @history.dup.drop('Open','High','Low','Close','Adj Close', 'Volume')
    return df.filter((Polars.col('Stock Splits')>0.0) | (Polars.col('Dividends')>0.0) | (Polars.col('Capital Gains')>0.0)) #Polars::DataFrame.new(stspl)
  end
  return Polars::Series.new
end

#capital_gainsObject



225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/yfinrb/price_history.rb', line 225

def capital_gains
  history(period: "max") if @history.nil?

  if !@history.nil? # && @history['events'].keys.include?("capital gains")
    # caga = []
    # @history['events']['capital gains'].each_pair {|k,v| caga << { Timestamps: Time.at(k).utc.to_date, Value: v['amount']} }
    # capital_gains = @history["Capital Gains"]
    # return capital_gains[capital_gains != 0]
    # Rails.logger.info { "#{__FILE__}:#{__LINE__} @history = #{@history.inspect}" }
    df = @history.dup.drop('Open','High','Low','Close','Adj Close', 'Volume','Stock Splits', 'Dividends')
    return df.filter(Polars.col('Capital Gains')>0.0)
  end
  return Polars::Series.new
end

#currencyObject



272
273
274
275
276
277
278
279
# File 'lib/yfinrb/price_history.rb', line 272

def currency
  if @currency.nil?

    md =  #(proxy=self.proxy)
    @currency = md["currency"]
  end
  return @currency
end

#day_highObject



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/yfinrb/price_history.rb', line 373

def day_high
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} @day_high = #{@day_high}" }
  return @day_high unless @day_high.nil?

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} @day_high = #{@day_high}" }
  prices = _get_1y_prices
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} prices = #{prices.inspect}" }
  # if prices.empty?
  #   @day_high = nil

  # else
  @day_high = (prices["High"][-1])
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} @day_high = #{@day_high}" }
  @day_high = nil if @day_high.nan?
  # end

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} @day_high = #{@day_high}" }
  return @day_high
end

#day_lowObject



393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/yfinrb/price_history.rb', line 393

def day_low
  return @day_low unless @day_low.nil?

  prices = _get_1y_prices
  if prices.empty?
    @day_low = nil

  else
    @day_low = (prices["Low"][-1])
    @day_low = nil if @day_low.nan?
  end

  return @day_low
end

#dividendsObject



212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/yfinrb/price_history.rb', line 212

def dividends
  history(period: "max") if @history.nil?

  if !@history.nil? # && @history['events'].keys.include?("dividends")
    df = @history.dup.drop('Open','High','Low','Close','Adj Close', 'Volume','Stock Splits','Capital Gains')
    return df.filter(Polars.col('Dividends')>0.0)
    # divi = []
    # @history['events']["dividends"].each_pair {|k,v| divi << { Timestamps: Time.at(k.to_i).utc.to_date, Value: v['amount']} }
    # return Polars::DataFrame.new( divi )
  end
  return Polars::Series.new
end

#exchangeObject



204
205
206
# File 'lib/yfinrb/price_history.rb', line 204

def exchange
  return @exchange ||= ["exchangeName"]
end

#fifty_day_averageObject



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/yfinrb/price_history.rb', line 416

def fifty_day_average
  return @_50d_day_average unless @_50d_day_average.nil?

  prices = _get_1y_prices(fullDaysOnly=true)
  if prices.empty?
    @_50d_day_average = nil

  else
    n = prices.shape.first
    a = n-50
    b = n
    a = 0 if a < 0

    @_50d_day_average = (prices["Close"][a..b].mean)
  end

  return @_50d_day_average
end

#history(period: "1mo", interval: "1d", start: nil, fin: nil, prepost: false, actions: true, auto_adjust: true, back_adjust: false, repair: false, keepna: false, rounding: false, raise_errors: false, returns: false) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/yfinrb/price_history.rb', line 35

def history(period: "1mo", interval: "1d", start: nil, fin: nil, prepost: false,
            actions: true, auto_adjust: true, back_adjust: false, repair: false, keepna: false,
            rounding: false, raise_errors: false, returns: false)
  logger = Rails.logger # Yfin.get_yf_logger
  start_user = start
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} here" }
  end_user = fin || DateTime.now

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} here" }
  params = _preprocess_params(start, fin, interval, period, prepost, raise_errors)
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} params=#{params.inspect}" }

  params_pretty = params.dup

  ["period1", "period2"].each do |k|
    params_pretty[k] = DateTime.strptime(params[k].to_s, '%s').new_offset(0).to_time.strftime('%Y-%m-%d %H:%M:%S %z') if params_pretty.key?(k)
  end

  data = _get_data(ticker, params, fin, raise_errors)
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} data = #{data.inspect}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} data[chart][result].first.keys = #{data['chart']['result'].first.keys.inspect}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} data[chart][result].first[events] = #{data['chart']['result'].first['events'].inspect}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} data[chart][result].first[events][dividends] = #{data['chart']['result'].first['events']['dividends'].inspect}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} data[chart][result].first[events][splits] = #{data['chart']['result'].first['events']['splits'].inspect}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} @history = #{@history.inspect}" }

  @history_metadata = data["chart"]["result"][0]["meta"] rescue {}
  @history = data["chart"]["result"][0]

  intraday = params["interval"][-1] == "m" || params["interval"][-1] == "h"

  err_msg = _get_err_msg(params['period1'], period, start, params['period2'], fin, params['interval'], params['intraday'])
  # err_msg = _get_err_msg(start, period, start_user, fin, end_user, interval, intraday)
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} err_msg = #{err_msg}" }

  f = _did_it_fail(data, period, @history_metadata)
  failed = f[:fail]
  err_msg = f[:msg]

  if failed
    if raise_errors
      raise Exception.new("#{ticker}: #{err_msg}")
    else
      logger.error("#{ticker}: #{err_msg}")
    end
    if @reconstruct_start_interval && @reconstruct_start_interval == interval
      @reconstruct_start_interval = nil
    end
    return Yfinrb::Utils.empty_df
  end

  # begin
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} data[chart][result][0] = #{data["chart"]["result"][0].inspect}" }
  quotes = _parse_quotes(data["chart"]["result"][0], interval)
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} @history = #{@history.inspect}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} data = #{data.inspect}" }

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} quotes=#{quotes.inspect}" }
  # if fin && !quotes.empty?
  #   endDt = fin.to_datetime.to_i # DateTime.strptime(fin.to_s, '%s').new_offset(0)
  #   if quotes.index[quotes.shape[0] - 1] >= endDt
  #     quotes = quotes[0..quotes.shape[0] - 2]
  #   end
  # end

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} here" }
  # rescue Exception
  #   if raise_errors
  #     raise Exception.new("#{ticker}: #{err_msg}")
  #   else
  #     logger.error("#{ticker}: #{err_msg}")
  #   end
  #   if @reconstruct_start_interval && @reconstruct_start_interval == interval
  #     @reconstruct_start_interval = nil
  #   end
  #   return nil
  # end

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} here" }
  quote_type = @history_metadata["instrumentType"]
  expect_capital_gains = quote_type == 'MUTUALFUND' || quote_type == 'ETF'
  tz_exchange = @history_metadata["exchangeTimezoneName"]

  quotes = _set_df_tz(quotes, params["interval"], tz_exchange)
  quotes = _fix_yahoo_dst_issue(quotes, params["interval"])
  quotes = _fix_yahoo_returning_live_separate(quotes, params["interval"], tz_exchange)

  intraday = params["interval"][-1] == "m" || params["interval"][-1] == "h"

  if !prepost && intraday && @history_metadata.key?("tradingPeriods")
    tps = @history_metadata["tradingPeriods"]
    if !tps.is_a?(Polars::DataFrame)
      @history_metadata = (@history_metadata, tradingPeriodsOnly: true)
      tps = @history_metadata["tradingPeriods"]
    end
    quotes = _fix_yahoo_returning_prepost_unrequested(quotes, params["interval"], tps)
  end

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} quotes = #{quotes.inspect}" }
  df = _get_stock_data(quotes, params, fin)
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} df = #{df.inspect}" }

  if repair
    #   df = _fix_unit_mixups(df, interval, tz_exchange, prepost)
    #   df = _fix_bad_stock_split(df, interval, tz_exchange)
    #   df = _fix_zeroes(df, interval, tz_exchange, prepost)
    #   df = _fix_missing_div_adjust(df, interval, tz_exchange)
    #   df = df.sort_index
  end

  if auto_adjust
    #   df = _auto_adjust(df)
  elsif back_adjust
    #   df = _back_adjust(df)
  end

  if rounding
    # df = df.round(data["chart"]["result"][0]["meta"]["priceHint"])
  end

  df["Volume"] = df["Volume"].fill_nan(0) #.astype(Integer)

  # df.index.name = intraday ? "Datetime" : "Date"
  # [0..df['Timestamps'].length-2].each{|i| df['Timestamps'][i] = df['Timestamps'][i].round("1d") } unless intraday
  unless intraday
    s = Polars::Series.new(df['Timestamps']).to_a
    df['Timestamps'] = (0..s.length-1).to_a.map{|i| Time.at(s[i]).to_date }
  end

  @history = df.dup

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} actions = #{actions}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} @history = #{@history.inspect}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} df = #{df.inspect}" }
  df = df.drop(["Dividends", "Stock Splits", "Capital Gains"], errors: 'ignore') unless actions

  if !keepna
      # price_colnames = ['Open', 'High', 'Low', 'Close', 'Adj Close']
      # data_colnames = price_colnames + ['Volume'] + ['Dividends', 'Stock Splits', 'Capital Gains']
      # data_colnames = data_colnames.select { |c| df.columns.include?(c) }
      # mask_nan_or_zero = (df[data_colnames].isnan? | (df[data_colnames] == 0)).all(axis: 1)
      # df = df.drop(mask_nan_or_zero.index[mask_nan_or_zero])
  end

  # logger.debug("#{ticker}: yfinance returning OHLC: #{df.index[0]} -> #{df.index[-1]}")

  @reconstruct_start_interval = nil if @reconstruct_start_interval && @reconstruct_start_interval == interval

  # Rails.logger.info { "#{__FILE__}:#{__LINE__} df = #{df.inspect}" }
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} df.rows = #{df.rows}" }
  if returns && df.shape.first > 1
    df['Returns'] = [Float::NAN] + (1..df.length-1).to_a.map {|i| (df['Close'][i]-df['Close'][i-1])/df['Close'][i-1] }
  end
  # Rails.logger.info { "#{__FILE__}:#{__LINE__} df = #{df.inspect}" }

  return df
end

#history_metadataObject



194
195
196
197
198
199
200
201
202
# File 'lib/yfinrb/price_history.rb', line 194

def 
  history(period: "1wk", interval: "1h", prepost: true) if @history_metadata.nil?

  if !@history_metadata_formatted
    @history_metadata = (@history_metadata)
    @history_metadata_formatted = true
  end
  return @history_metadata
end

#initialize_price_historyObject

(ticker)



24
25
26
27
28
29
30
31
32
33
# File 'lib/yfinrb/price_history.rb', line 24

def initialize_price_history #(ticker)
  # ticker = ticker

  @history = nil
  @history_metadata = nil
  @history_metadata_formatted = false
  @reconstruct_start_interval = nil

  yfconn_initialize
end

#last_priceObject



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/yfinrb/price_history.rb', line 290

def last_price
  return @last_price unless @last_price.nil?

  prices = _get_1y_prices

  if prices.empty?
    @md ||= 
    @last_price = md["regularMarketPrice"] if "regularMarketPrice".in?(@md)

  else
    @last_price = (prices["Close"][-1]).to_f
    if @last_price.nan?
      @md ||= 
      @last_price = md["regularMarketPrice"] if "regularMarketPrice".in?(@md)
    end
  end

  return @last_price
end

#last_volumeObject



408
409
410
411
412
413
414
# File 'lib/yfinrb/price_history.rb', line 408

def last_volume
  return @last_volume unless @last_volume.nil?

  prices = _get_1y_prices
  @last_volume = prices.empty? ? nil : (prices["Volume"][-1])
  return @last_volume
end

#market_capObject



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/yfinrb/price_history.rb', line 517

def market_cap
  return @mcap unless @mcap.nil?

  begin
    # shares = self.shares
    # Rails.logger.info { "#{__FILE__}:#{__LINE__} shares = #{shares}" }
    sh = shares
    lp = last_price
    @mcap = shares * last_price
    # @mcap = 'US$' + number_to_human((shares * last_price), precision: 4)
  rescue Exception => e
    if "Cannot retrieve share count".in?(e.message) || "failed to decrypt Yahoo".in?(e.message)
      shares = nil
    else
      raise
    end

    # if shares.nil?
    #   # Very few symbols have marketCap despite no share count.
    #   # E.g. 'BTC-USD'
    #   # So fallback to original info[] if available.
    #   info
    #   k = "marketCap"
    #   @mcap = _quote._retired_info[k] if !_quote._retired_info.nil? && k.in?(_quote._retired_info)

    # else
    #   @mcap = float(shares * self.last_price)
    # end

    return nil #@mcap
  end
end

#openObject



358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/yfinrb/price_history.rb', line 358

def open
  return @open unless @open.nil?

  prices = _get_1y_prices
  if prices.empty
    @open = nil

  else
    @open = (prices["Open"][-1])
    @open = nil if @open.nan?
  end

  return @open
end

#previous_closeObject



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/yfinrb/price_history.rb', line 310

def previous_close
  return @prev_close unless @prev_close.nil?

  prices = _get_1wk_1h_prepost_prices

  fail = prices.empty?
  prices = fail ? prices : prices[["Close"]].groupby('Timestamps', maintain_order: true).agg([Polars.col("Close")]).to_f 

  # Very few symbols have previousClose despite no
  # no trading data e.g. 'QCSTIX'.
  fail = prices.shape.first < 2
  @prev_close = fail ? nil : (prices["Close"][-2]).to_f

  # if fail
  #   # Fallback to original info[] if available.
  #   info  # trigger fetch
  #   k = "previousClose"
  #   @prev_close = _quote._retired_info[k] if !_quote._retired_info.nil? && k.in?(_quote._retired_info)
  # end
  return @prev_close
end

#quote_typeObject



281
282
283
284
285
286
287
288
# File 'lib/yfinrb/price_history.rb', line 281

def quote_type
  if @quote_type.nil?

    md =  #(proxy=self.proxy)
    @quote_type = md["instrumentType"]
  end
  return @quote_type
end

#regular_market_previous_closeObject



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/yfinrb/price_history.rb', line 332

def regular_market_previous_close
  return @reg_prev_close unless @reg_prev_close.nil?

  prices = _get_1y_prices
  if prices.shape[0] == 1
    # Tiny % of tickers don't return daily history before last trading day,
    # so backup option is hourly history:
    prices = _get_1wk_1h_reg_prices
    prices = prices[["Close"]].groupby(prices.index.date).last
  end

  # if prices.shape[0] < 2
  #   # Very few symbols have regularMarketPreviousClose despite no
  #   # no trading data. E.g. 'QCSTIX'.
  #   # So fallback to original info[] if available.
  #   info  # trigger fetch
  #   k = "regularMarketPreviousClose"
  #   @reg_prev_close = _quote._retired_info[k] if !_quote._retired_info.nil? && k.in?(_quote._retired_info)

  # else
  #   @reg_prev_close = float(prices["Close"].iloc[-2])
  # end

  return @reg_prev_close
end

#splitsObject



240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/yfinrb/price_history.rb', line 240

def splits
  history(period: "max") if @history.nil?

  if !@history.nil?  #&& @history['events'].keys.include?("stock splits") # @history.columns.include?("Stock Splits")
    # stspl = []
    # @history['events']['stock splits'].each_pair {|k,v| stspl << { Timestamps: Time.at(k.to_i).utc.to_date, Ratio: v['numerator'].to_f/v['denominator'].to_f } }

    # splits = @history["Stock Splits"]
    # return splits[splits != 0]
    df = @history.dup.drop('Open','High','Low','Close','Adj Close', 'Volume','Capital Gains','Dividends')
    return df.filter(Polars.col('Stock Splits')>0.0) #Polars::DataFrame.new(stspl)
  end
  return Polars::Series.new
end

#ten_day_average_volumeObject



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/yfinrb/price_history.rb', line 454

def ten_day_average_volume
  return @_10d_avg_vol unless @_10d_avg_vol.nil?

  prices = _get_1y_prices(fullDaysOnly=true)
  if prices.empty?
    @_10d_avg_vol = nil

  else
    n = prices.shape[0]
    a = n-10
    b = n
    a = 0 if a < 0

    @_10d_avg_vol = (prices["Volume"][a..b].mean)

  end
  return @_10d_avg_vol
end

#three_month_average_volumeObject



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/yfinrb/price_history.rb', line 473

def three_month_average_volume
  return @_3mo_avg_vol unless @_3mo_avg_vol.nil?

  prices = _get_1y_prices(fullDaysOnly=true)
  if prices.empty
    @_3mo_avg_vol = nil

  else
    dt1 = prices.index[-1]
    dt0 = dt1 - 3.months + 1.day
    @_3mo_avg_vol = (prices[dt0..dt1]["Volume"].mean)
  end

  return @_3mo_avg_vol
end

#timezoneObject



208
209
210
# File 'lib/yfinrb/price_history.rb', line 208

def timezone
  return @timezone ||= ["exchangeTimezoneName"]
end

#two_hundred_day_averageObject



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/yfinrb/price_history.rb', line 435

def two_hundred_day_average
  return @_200d_day_average unless @_200d_day_average.nil?

  prices = _get_1y_prices(fullDaysOnly=true)
  if prices.empty?
    @_200d_day_average = nil

  else
    n = prices.shape[0]
    a = n-200
    b = n
    a = 0 if a < 0

    @_200d_day_average = (prices["Close"][a..b].mean)
  end

  return @_200d_day_average
end

#year_changeObject



509
510
511
512
513
514
515
# File 'lib/yfinrb/price_history.rb', line 509

def year_change
  if @year_change.nil?
    prices = _get_1y_prices(fullDaysOnly=true)
    @year_change = (prices["Close"][-1] - prices["Close"][0]) / prices["Close"][0] if prices.shape[0] >= 2
  end
  return @year_change
end

#year_highObject



489
490
491
492
493
494
495
496
497
# File 'lib/yfinrb/price_history.rb', line 489

def year_high
  if @year_high.nil?
    prices = _get_1y_prices(fullDaysOnly=true)
    prices = _get_1y_prices(fullDaysOnly=false) if prices.empty?

    @year_high = (prices["High"].max)
  end
  return @year_high
end

#year_lowObject



499
500
501
502
503
504
505
506
507
# File 'lib/yfinrb/price_history.rb', line 499

def year_low
  if @year_low.nil?
    prices = _get_1y_prices(fullDaysOnly=true)
    prices = _get_1y_prices(fullDaysOnly=false) if prices.empty?

    @year_low = (prices["Low"].min)
  end
  return @year_low
end