我正在开发一个程序,该程序使用 yahoo Finance api 收集输入股票数量的历史收盘数据,然后继续计算 30 天数据的简单移动平均线 (SMA)。到目前为止,我有以下内容:
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
此代码为我提供了指定范围内股票的收盘价。我有两个问题:
目前,
hq.close
持有所有股票的价值。如何将这些值放入数组中,以便对其进行计算以计算每个股票数据的 SMA?我试着做这样的事情:
"#{hq.close}" my_val = [hq.close] puts my_val
但这仅给出了第一个股票的价值
my_val
。我知道我必须在这里放一个循环。我试着把while(!hq.close.emply?) my_val = [hq.close] puts my_val end
但这给了我一个错误:
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
如何在 Ruby 中计算 SMA?