I am working on a program that uses yahoo finance api to collect the historical close data for the number of stocks entered and then go ahead and calculate simple moving average (SMA) for the data for period of 30 days. I have the following so far:
require 'rubygems'
require 'yahoofinance'
array = []
while line = gets
break if line.chomp =~ /N/ #exit when 'N' is entered
array << line.chomp
end
puts "Values: #{array.join(',')}" #joining all the elements with a comma
array.each do |s|
print "\n______\n"
puts s
YahooFinance::get_HistoricalQuotes( s,
Date.parse( '2012-10-06' ),
Date.today() ) do |hq|
puts "#{hq.close}"
end
end
This code is giving me the close values for stocks for the specified range. I have two questions:
-
Currently,
hq.closeis holding values for all stocks. How can I put these values in an array so that I can do a computation on it to calculate a SMA for each stock data?I tried doing something like this:
"#{hq.close}" my_val = [hq.close] puts my_valBut this only gives the value of first stock in
my_val. I know I have to put a loop here. I tried puttingwhile(!hq.close.emply?) my_val = [hq.close] puts my_val endBut this gives me an error:
C:/Users/Muktak/workspace/RubySample/sample_program.rb:23:in block (2 levels) in <main>': undefined methodemplty?' for 19.52:Float (NoMethodError) from C:/Ruby193/lib/ruby/gems/1.9.1/gems/yahoofinance-1.2.2/lib/yahoofinance.rb:491:in block in get_HistoricalQuotes' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/yahoofinance-1.2.2/lib/yahoofinance.rb:456:inblock in get_historical_quotes' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/yahoofinance-1.2.2/lib/yahoofinance.rb:456:in each' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/yahoofinance-1.2.2/lib/yahoofinance.rb:456:inget_historical_quotes' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/yahoofinance-1.2.2/lib/yahoofinance.rb:489:in get_HistoricalQuotes' from C:/Users/Muktak/workspace/RubySample/sample_program.rb:19:inblock in ' from C:/Users/Muktak/workspace/RubySample/sample_program.rb:13:in each' from C:/Users/Muktak/workspace/RubySample/sample_program.rb:13:in' Values: FB,GOOG -
How can I calculate a SMA in Ruby?
You’ve asked two questions here, so let’s address them one at a time.
First, this code:
… will produce the following hash in
closes, which I understand is in the format you want:Secondly, you want to calculate a simple moving average – which for financial applications is just the mean of the values. There is a Gem called simple_statistics that can do this.
This code:
… produces the following hash in
averages: