無料で使えるシステムトレードフレームワーク「Jiji」 をリリースしました!

・OANDA Trade APIを利用した、オープンソースのシステムトレードフレームワークです。
・自分だけの取引アルゴリズムで、誰でも、いますぐ、かんたんに、自動取引を開始できます。

指定銘柄の一定期間の株価を取得するRubyプログラム

遙か昔に書いた、指定した銘柄の一定期間の株価を取得してくるプログラムです。Yahoo! ファイナンス 株価・投信・為替時系列データにアクセスしてスクレイピングでデータを抽出しています。

使い方

引数で銘柄コード、取得開始日、終了日を指定します。

put_stock_prices( 1234, Date.new( 2007, 4, 1 ), Date.new( 2007, 11, 1 ), "http://proxyhost:80")

出力イメージは以下。「日付 始値 終値 高値 安値 出来高」の順に並びます。

2007年11月1日 665 647 670 643 154200
2007年10月31日 666 660 677 656 107900
2007年10月30日 650 678 680 640 389600
2007年10月29日 692 690 718 681 247400
2007年10月26日 659 683 683 659 82800
2007年10月25日 662 656 683 654 151300
2007年10月24日 693 672 695 668 107400
2007年10月23日 696 683 705 678 128400
2007年10月22日 650 678 682 650 150700
2007年10月19日 708 690 715 676 169100
...

依存モジュール

httpclientHpricotを利用しています。
以下のコマンドを実行してインストールしてください。

gem install hpricot
gem install httpclient --source http://dev.ctor.org/download/

実装

require 'rubygems'
require 'hpricot'
require 'httpclient'
require 'date'
require 'kconv'

# 一定期間の株価を取得する。
# @param company_code 企業コード
# @param start_date 開始日
# @param end_date 終了日
# @param proxy プロキシの指定 (http://<プロキシホスト>:<プロキシポート>)
def put_stock_prices ( company_code, start_date, end_date, proxy=nil )
  i = 0
  loop {
    client = HTTPClient.new(proxy)

    uri = "http://table.yahoo.co.jp/t?g=d&q=t&x=.csv&z=4876"
    uri << "&s=" << company_code.to_s
    uri << "&a=" << start_date.mon.to_s
    uri << "&b=" << start_date.day.to_s
    uri << "&c=" << start_date.year.to_s
    uri << "&d=" << end_date.mon.to_s
    uri << "&e=" << end_date.day.to_s
    uri << "&f=" << end_date.year.to_s
    uri << "&y=" << (i*50).to_s
    res = client.get( uri );

    doc = Hpricot(res.content)
    tmp = doc/"table[@cellpadding='5']"
    raise "not found" if tmp == nil || tmp.length < 1

    inserted = false
    tmp.each { |table|
      (table/"tr").each { |tr|
        tds = tr/"td"
        if ( tds.length > 4 && tds[0].inner_text.toutf8 =~ /(\d+)(\d+)(\d+)/ )
          puts [tds[0].inner_text.toutf8, tds[1].inner_text, tds[4].inner_text,
             tds[2].inner_text, tds[3].inner_text, tds[5].inner_text].join(" ").gsub(/,/, "").tosjis
          inserted = true
        end
      }
    }
    i += 1
    break if !inserted
  }
end