Class: Iro::Stock

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document, Mongoid::Paranoia, Mongoid::Timestamps
Defined in:
app/models/iro/stock.rb

Constant Summary collapse

STATUS_ACTIVE =
'active'
STATUS_INACTIVE =
'inactive'
STATUSES =
[ nil, 'active', 'inactive' ]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.activeObject



13
14
15
# File 'app/models/iro/stock.rb', line 13

def self.active
  where( status: STATUS_ACTIVE )
end

.f(ticker) ⇒ Object



32
33
34
# File 'app/models/iro/stock.rb', line 32

def self.f ticker
  self.find_by ticker: ticker
end

.listObject



39
40
41
# File 'app/models/iro/stock.rb', line 39

def self.list
  [[nil,nil]] + all.map { |sss| [ sss.ticker, sss.id ] }
end

.tickers_listObject



42
43
44
# File 'app/models/iro/stock.rb', line 42

def self.tickers_list
  [[nil,nil]] + all.map { |sss| [ sss.ticker, sss.ticker ] }
end

Instance Method Details

#stdev(recompute: nil) ⇒ Object



96
97
98
99
100
101
102
103
104
105
# File 'app/models/iro/stock.rb', line 96

def stdev recompute: nil
  if !self[:stdev] || recompute
    out = volatility_from_yr
    self[:stdev] = out
    save( validate: false )
    return out
  else
    self[:stdev]
  end
end

#to_sObject



36
37
38
# File 'app/models/iro/stock.rb', line 36

def to_s
  ticker
end

#volatility(duration:) ⇒ Object

stock = Iro::Stock.find_by( ticker: ‘NVDA’ )

duration = 1.month
stock.volatility_from_mo

duration = 1.year
stock.volatility_from_yr


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
# File 'app/models/iro/stock.rb', line 56

def volatility duration:
  stock = self
  begin_on = Time.now - duration - 1.day
  points = Iro::Datapoint.where( kind: 'STOCK', symbol: stock.ticker,
    :date.gte => begin_on,
  ).order_by( date: :asc )

  puts! [points.first.date, points.last.date], "from,to"

  points_p = []
  points.each_with_index do |p, idx|
    next if idx == 0
    prev = points[idx-1]

    out = p.value / prev.value - 1
    points_p.push out
  end
  n = points_p.length

  avg = points_p.reduce(&:+) / n
  _sum_of_sq = []
  points_p.map do |p|
    _sum_of_sq.push( ( p - avg )*( p - avg ) )
  end
  sum_of_sq = _sum_of_sq.reduce( &:+ ) / n

  # n_periods = begin_on.to_date.business_days_until( Date.today )
  out = Math.sqrt( sum_of_sq )*sqrt( n )
  adjustment = 2.0
  out = out * adjustment
  puts! out, 'volatility (adjusted)'
  return out
end

#volatility_from_moObject



90
91
92
# File 'app/models/iro/stock.rb', line 90

def volatility_from_mo
  volatility( duration: 1.month )
end

#volatility_from_yrObject



93
94
95
# File 'app/models/iro/stock.rb', line 93

def volatility_from_yr
  volatility( duration: 1.year )
end