Search code examples
ruby

issue with yahoofinance ruby api return value


I know joining arrays and strings but this issue is very specific to an api I am working on :

All I want is all hq.close value in an array. EG:

[
 {'GOOG' => [744.75,751.48,744.56,744.09,757.84]},
 {'MSFT' => {value1,value2, .....}}
]

Reason I am not able to get the above array of hash is because when I do puts hq.close its printing individual value and I am not sure how to get all hq.close into one array

Based on code below my output is line seperated : (but i want it in above format)

GOOG -> 744.75
GOOG -> 751.48
GOOG -> 744.56
GOOG -> 744.09
GOOG -> 757.84
MSFT -> 29.2
MSFT -> 28.95
MSFT -> 28.98
MSFT -> 29.28
MSFT -> 29.78

+++++++++++++++++++++++++++ Code:

require 'yahoofinance'
#Stock symbols
user_input = ['GOOG','MSFT']

user_input.each do|symb|
 YahooFinance::get_HistoricalQuotes( symb,
                                     Date.parse('2012-10-06'),
                                     Date.today()) do |hq|
   puts "#{symb} -> #{hq.close}"
  end
end

Solution

  • You could inject over each value to build your hash:

    require 'yahoofinance'
    
    company_symbols = ['GOOG','MSFT']
    start_date = Date.parse('2012-10-06')
    stop_date = Date.today()
    
    company_symbols.inject({}) do |memo, value|
      memo[value] ||= []
      YahooFinance.get_HistoricalQuotes(value, start_date, stop_date) do |hq|
        memo[value] << hq.close
      end
      memo
    end
    # => {"GOOG"=>[744.75, 751.48, 744.56, 744.09, 757.84], "MSFT"=>[29.2, 28.95, 28.98, 29.28, 29.78]}