Sunday, June 08, 2008

Ruby Stock

Infoseekの株価データにアクセスして必要な情報を取得する。
サマリーとヒストリー

Stock.rb

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

#!/usr/bin/env ruby -wKU

# encoding: utf-8

require "rubygems"

require "hpricot"

require "open-uri"

require "kconv"


class Stock

  attr_reader :name, :category, :data, :price_data, :credit_data, :company_data, :value_data

  def initialize(code)

    @code = code

    main_data(@code)

  end

  

  def price_history(term,method='m',start_page=0) #method:m,w,d, sstart_page:0,50,100

    begin

      url = "http://money.www.infoseek.co.jp/MnStock/#{@code}/slast/?sy=#{term[0][0]}&sm=#{term[0][1]}&sd=#{term[0][2]}&ey=#{term[1][0]}&em=#{term[1][1]}&ed=#{term[1][1]}&k=#{method}&st=#{start_page}"

      doc = Hpricot(open(url))

      price_history = []

      (doc/"table.ruled"/:tbody/:tr).each do |elem|

        begin

          price_history << [elem.at(:th).inner_text.toutf8, elem.at("td.emph").inner_text.toutf8]

        rescue Exception => e

          price_history << [elem.at(:th).inner_text.toutf8, nil]

          p e

        end

      end

      price_history

    rescue Exception => e

      puts e

    ensure

    end

  end

  

  private

  def main_data(code)

    begin

      url = "http://money.www.infoseek.co.jp/MnStock/#{code}/sresult/"

      data =Hpricot(open(url))

      (data/"h3#description").each do |elem|

        begin

          @name = elem.at("span#dname").inner_text.toutf8

          @category = elem.at("span#dname").next_sibling.inner_text.gsub(/\s|\?/,"").toutf8

        rescue Exception => e

          

        end

      end

      @data = []

      (data/"table.ruled").each do |table|

        begin

          @data << table.inner_text.toutf8.to_a.reject{ |item| item == "\n" }.each { |item| item.delete!("\n")}

          @price_data, @credit_data, @company_data, *@value_data = *@data

        rescue Exception => e

          

        end

      end

    rescue Exception => e

      puts e

    end

  end

  

end


if __FILE__ == $0

  stocks = ['2678.t', '3382.t', '4659.j', '7974.t', '8227.t', '9064.t', '9983.t']

  term = [[2005,1,1],[2008,6,30]]

  start_page = 0

  method = 'm'

  

  stocks.each do |stock|

    stk = Stock.new(stock)

    puts stk.name

    puts stk.category

    p stk.value_data

    p stk.price_history(term, method, start_page)

  end


end

No comments: