2
我正在使用雅虎財經API收集輸入股票數量的歷史收盤數據的程序,然後繼續計算數據的簡單移動平均線(SMA) 30天。我目前有以下幾種:如何計算簡單移動平均線
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?
沒有''emply方法,''空而另一方面...? –
嗨,感謝您指出錯字錯誤。但即使在改正之後,我仍然會遇到同樣的錯誤。我正在考慮另一種方法。由於hq.close包含股票代碼及其結束值的列表,我可以在這個對象上做兩個循環,第一個用於遍歷該對象以獲取列表數量,第二個獲取列表中的相應值。我知道這在Java中是非常有可能的。有沒有辦法在ruby中做到這一點?請舉一個例子 – user1745117