2

我正在开发一个程序,该程序使用 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

此代码为我提供了指定范围内股票的收盘价。我有两个问题:

  1. 目前,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
    
  2. 如何在 Ruby 中计算 SMA?

4

1 回答 1

2

您在这里提出了两个问题,所以让我们一次解决一个问题。

首先,这段代码:

require 'rubygems'
require 'yahoofinance'

stock_names = %w{MSFT RHT AAPL}
start = Date.parse '2012-10-06'
finish = Date.today
closes = {}

stock_names.each do |stock_name|
  quotes = YahooFinance::get_HistoricalQuotes stock_name, start, finish
  closes[stock_name] = quotes.collect { |quote| quote.close }
end

... 将在 中产生以下哈希closes,我理解它是您想要的格式:

{
  "AAPL" => [629.71, 628.1, 640.91, 635.85, 638.17],
  "RHT"=> [53.69, 53.77, 53.86, 54.0, 54.41],
  "MSFT"=> [29.2, 28.95, 28.98, 29.28, 29.78]
}

其次,你想计算一个简单的移动平均线——对于金融应用来说,它只是这些值的平均值。有一个名为 simple_statistics 的 Gem 可以做到这一点。

这段代码:

require 'rubygems'
require 'yahoofinance'
require 'simple_statistics'

stock_names = %w{MSFT RHT AAPL}
start = Date.parse '2012-10-06'
finish = Date.today
averages = {}

stock_names.each do |stock_name|
  quotes = YahooFinance::get_HistoricalQuotes stock_name, start, finish
  closes = quotes.collect { |quote| quote.close }
  averages[stock_name] = closes.mean
end

...在 中产生以下哈希averages

{ "AAPL" => 634.548, "MSFT" => 29.238, "RHT" => 53.946 }
于 2012-10-15T02:08:55.797 回答