Method: Market.fetch

Defined in:
lib/market.rb

.fetch(ticker, opts = {}) ⇒ Object



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
# File 'lib/market.rb', line 66

def fetch(ticker, opts = {})
  url = "http://finance.yahoo.com/q?s=%s" % ticker
  puts "Fetching #{url}..." if $VERBOSE

  doc = with_retry do
    Nokogiri::HTML.parse(get(url))
  end

  # Realtime last is at yfs_l90_sym, use if exists
  if opts[:try_rt]
    last = (doc.at_css("#yfs_l90_#{ticker.downcase}").text.to_f * 100) rescue nil
  end

  last ||= (doc.at_css("#yfs_l10_#{ticker.downcase}").text.to_f * 100)
  bid  = (doc.at_css("#yfs_b00_#{ticker.downcase}").text.to_f * 100) rescue 0
  ask  = (doc.at_css("#yfs_a00_#{ticker.downcase}").text.to_f * 100) rescue 0

  quote = Quote.new(
    :symbol => ticker, :last => last, :bid => bid, :ask => ask)

  if opts[:extra]
    name   = doc.at('h1').text.scan(/(.*) \([\w-]+\)$/).to_s # strip trailing (SYMBOL)
    mktcap = doc.at_css("#yfs_j10_#{ticker.downcase}").text rescue nil

    divyield = doc.at("#table2 .end td").text.scan(/\((.*)\)/).to_s.to_f rescue nil

    begin
      pe_row = doc.at("#table2 tr:nth-child(6)")
      pe_label, pe_data = pe_row.search("th,td").map{|e|e.text}

      unless pe_label =~ %r(P/E)
        puts "P/E label mismatch" 
        pe_data = nil
      end
    rescue
      # nothing
    end

    sector, industry = doc.search("#company_details a").map{|e|e.text} rescue nil

    quote.extra = {
      :name => name,
      :mktcap => mktcap,
      :divyield => divyield,
      :pe => pe_data.to_f,
      :sector => sector,
      :industry => industry
    }
  end

  puts quote.inspect if $VERBOSE

  quote
end