greenmonster 0.1.0.pre

Sign up to get free protection for your applications and to get access to all the features.
data/README.markdown ADDED
@@ -0,0 +1,57 @@
1
+ Greenmonster
2
+ ============
3
+
4
+ Greenmonster is a toolkit for baseball stat enthusiasts or sabermetricians to build a database of
5
+ play-by-play stats from MLB's [Gameday XML data](http://gd.mlb.com/components/game/).
6
+
7
+ The pre-release gem is currently spiders games from MLB's servers. I will be extracting pieces out
8
+ of my toolkit to parse Gameday XML data to produce play-by-play database of MLB and MiLB stats.
9
+
10
+ Usage
11
+ -----
12
+
13
+ The spider utility has two public class methods: Spider.pull_day and Spider.pull_days.
14
+
15
+ Spider.pull_day takes an hash of options as an argument. The only mandatory argument option
16
+ is to specify :games_folder, which is the local folder where you want to store the game files.
17
+ Greenmonster will create subfolders by MLB "sport_code" (MLB games fall under 'mlb', various
18
+ minor league games and non-MLB/MiLB games fall under other sport code designations), and then
19
+ children folders for years, months, days, and specific games.
20
+
21
+ # Pulls all MLB games for today
22
+ => Greenmonster::Spider.pull_day({:date => Date.today, :games_folder => './home/geoff/games'})
23
+
24
+ # Pulls all rookie league games for today
25
+ > Greenmonster::Spider.pull_day({:sport_code => 'rok', :date => Date.today, :games_folder => './home/geoff/games'})
26
+
27
+
28
+ Spider.pull_days takes a range of dates to process as an argument, plus a hash of arguments to pass
29
+ to Spider.pull.
30
+
31
+ # Pulls all MLB games for in April, 2012
32
+ => Greenmonster::Spider.pull_days((Date.new(2012,4,1)..Date.new(2012,4,30)), {:games_folder => './home/geoff/games'})
33
+
34
+
35
+ Requirements
36
+ ------------
37
+ - Ruby 1.9
38
+ - Nokogiri
39
+ - HTTParty
40
+
41
+ Testing
42
+ -------
43
+
44
+ The test suite downloads a few days of data, so it is not fast to execute.
45
+
46
+
47
+ License
48
+ -------
49
+ (The MIT License)
50
+
51
+ Copyright © [Geoff Harcourt](http://github.com/geoffharcourt) 2012
52
+
53
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
54
+
55
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
56
+
57
+ THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require 'rake/testtask'
2
+
3
+ Rake::TestTask.new do |t|
4
+ t.libs << 'test'
5
+ end
6
+
7
+ desc "Run Tests"
8
+ task :default => :test
@@ -0,0 +1,125 @@
1
+ # The Gameday XML Spider utility
2
+ class Greenmonster::Spider
3
+ include HTTParty
4
+
5
+ ##
6
+ # Pull Gameday XML files for a given date. Default options for
7
+ # the spider are to pull games with sport_code of 'mlb' (games
8
+ # played by MLB games rather than MiLB teams or foreign teams)
9
+ # and to pull games on the current date. You must specify a
10
+ # :games_folder argument that is the root folder under which
11
+ # all games will be placed.
12
+ #
13
+ # Example:
14
+ # # Pull games from July 4, 2011
15
+ # >> Gameday::Spider.pull({:date => Date.new(2011,7,1), :games_location => '/Users/geoff/games'})
16
+ #
17
+ # Arguments:
18
+ # args: (Hash)
19
+
20
+ def self.pull_day(args = {})
21
+ args = {
22
+ :date => Date.today,
23
+ :league => 'mlb',
24
+ :print_games => true
25
+ }.merge(args)
26
+
27
+ raise "Games folder location required." if args[:games_folder].nil?
28
+
29
+ game_day_url_for_date = "http://gd2.mlb.com/components/game/#{args[:league]}/#{format_date_as_folder(args[:date])}"
30
+
31
+ # Iterate through every hyperlink on the page.
32
+ # These links represent the individual game folders
33
+ # for each date. Reject any links that aren't to game
34
+ # folders or that are to what look like backup game
35
+ # folders.
36
+ (Nokogiri::XML(self.get(game_day_url_for_date))/"a").reject{|l| l.attribute('href').value[0,4] != "gid_" or l.attribute('href').value[-5,4] == "_bak"}.each do |e|
37
+ puts e.attribute('href').value.gsub('/','') if args[:print_games]
38
+
39
+ paths = {
40
+ :localGameFolder => "#{args[:games_folder]}/#{args[:league]}/#{format_date_as_folder(args[:date])}/#{e.attribute('href').value}",
41
+ :mlbGameFolder => "#{game_day_url_for_date}/#{e.attribute('href').value}"
42
+ }
43
+
44
+ FileUtils.mkdir_p paths[:localGameFolder] + 'inning'
45
+
46
+ begin
47
+ # Always copy linescore first. If we can't get this
48
+ # data, all other game data is useless.
49
+ copy_gameday_xml('linescore.xml',paths)
50
+
51
+ if args[:date].year > 2007
52
+ copy_gameday_xml('inning_all.xml',paths)
53
+ copy_gameday_xml('inning_hit.xml',paths)
54
+ else
55
+ # Iterate through the inning files, but skip inning
56
+ # files numbered 0 (some bad spring training data).
57
+ # Necessary for games prior to 2008 because there is
58
+ # no inning_all.xml file in older games.
59
+ (Nokogiri::XML(self.get("#{paths[:mlbGameFolder]}/inning/").body).search('a')).each do |ic|
60
+ copy_gameday_xml(ic.attribute('href').value,paths) if ic.attribute('href').value[-3,3] == "xml" unless ic.attribute('href').value[-6,6] == "_0.xml" or ic.attribute('href').value.include?('Score')
61
+ end
62
+ end
63
+
64
+ # Copy base data files
65
+ # (if inning data wasn't there, this gets skipped)
66
+ ['boxscore.xml','eventLog.xml','players.xml'].each do |file|
67
+ copy_gameday_xml(file,paths)
68
+ end
69
+ rescue StandardError => bang
70
+ puts "Unable to download some data for #{e.attribute('href').value}"
71
+ end
72
+ end
73
+
74
+ game_day_url_for_date
75
+ end
76
+
77
+ ##
78
+ # Pull Gameday XML files for a range of dates. The args hash
79
+ # passes arguments like games_folder location on to Spider.pull.
80
+ #
81
+ # Example:
82
+ # # Pull all games in MLB in July 2011
83
+ # >> Gameday::Spider.pull_days(Date.new(2011,7,1)..Date.new(2011,7,31), {:games_location => '/Users/geoff/games'})
84
+ #
85
+ # Arguments:
86
+ # range: (Range)
87
+ # args: (Hash)
88
+
89
+ def self.pull_days(range,args = {})
90
+ range.each {|day| self.pull_day(args.merge({:date => day}))}
91
+ end
92
+
93
+ private
94
+ ##
95
+ # Copy XML files from the Gameday severs to your
96
+ # local machine for parsing and analysis. This method
97
+ # is used by Spider.pull to put files on your local
98
+ # machine in a similar layout to the one used by
99
+ # Gameday. The paths argument gets built by Spider.pull
100
+ # during the pull process.
101
+ #
102
+ # Arguments:
103
+ # file_name: (String)
104
+ # paths: (Hash)
105
+
106
+ def self.copy_gameday_xml (file_name,paths)
107
+ open(paths[:localGameFolder] + "#{file_name =~ /inning/ ? 'inning/' : ''}" + file_name, 'w') do |file|
108
+ file.write(self.get(paths[:mlbGameFolder] + "#{file_name =~ /inning/ ? 'inning/' : ''}" + file_name).body)
109
+ end
110
+ end
111
+
112
+ ##
113
+ # Output a folder format similar to the one used by Gameday.
114
+ #
115
+ # Example:
116
+ # Spider.format_date_as_folder(Date.new(2011,7,4))
117
+ # => "year_2011/month_07/day_04"
118
+ #
119
+ # Arguments:
120
+ # date: (Date)
121
+
122
+ def self.format_date_as_folder(date)
123
+ date.strftime("year_%Y/month_%m/day_%d")
124
+ end
125
+ end
@@ -0,0 +1,10 @@
1
+ require 'httparty'
2
+ require 'nokogiri'
3
+ require 'fileutils'
4
+
5
+ module Greenmonster
6
+
7
+
8
+ end
9
+
10
+ require 'greenmonster/spider'
@@ -0,0 +1,78 @@
1
+ require 'minitest/autorun'
2
+ require 'greenmonster'
3
+
4
+ class SpiderTest < MiniTest::Unit::TestCase
5
+ def setup
6
+ @local_test_data_location = "./greenmonster_test_games"
7
+ FileUtils.mkdir_p @local_test_data_location
8
+ end
9
+
10
+ def test_format_date_as_folder
11
+ assert_equal "year_2011/month_07/day_04", Greenmonster::Spider.format_date_as_folder(Date.new(2011,7,4))
12
+ assert_equal "year_2012/month_12/day_31", Greenmonster::Spider.format_date_as_folder(Date.new(2012,12,31))
13
+ end
14
+
15
+ def test_copy_gameday_xml
16
+ paths = {
17
+ :localGameFolder => "#{@local_test_data_location}/mlb/year_2011/month_05/day_03/gid_2011_05_03_sfnmlb_nynmlb_1/",
18
+ :mlbGameFolder => "http://gd2.mlb.com/components/game/mlb/year_2011/month_05/day_03/gid_2011_05_03_sfnmlb_nynmlb_1/"
19
+ }
20
+ FileUtils.mkdir_p paths[:localGameFolder] + 'inning'
21
+
22
+ %w(linescore.xml inning_all.xml).each do |f|
23
+ Greenmonster::Spider.copy_gameday_xml(f,paths)
24
+ end
25
+
26
+ assert_equal 287337, Nokogiri::XML(open(paths[:localGameFolder] + 'linescore.xml')).search("game").first.attribute('game_pk').value.to_i
27
+ assert_equal 10, Nokogiri::XML(open(paths[:localGameFolder] + 'inning/inning_all.xml')).search("inning").count
28
+ assert_equal 400023, Nokogiri::XML(open(paths[:localGameFolder] + 'inning/inning_all.xml')).search("atbat").first.attribute('batter').value.to_i
29
+ end
30
+
31
+ def test_pull_day
32
+ Greenmonster::Spider.pull_day({:print_games => false, :games_folder => @local_test_data_location, :date => Date.new(2011,6,7)})
33
+
34
+ assert_equal 17, Dir.entries(@local_test_data_location + '/mlb/year_2011/month_06/day_07/').count
35
+
36
+ game_location = @local_test_data_location + '/mlb/year_2011/month_06/day_07/gid_2011_06_07_bosmlb_nyamlb_1'
37
+ %w(linescore.xml boxscore.xml players.xml eventLog.xml inning).each do |f|
38
+ assert Dir.entries(game_location).include? f
39
+ end
40
+
41
+ boxscore = Nokogiri::XML(open(game_location + '/boxscore.xml'))
42
+ eventlog = Nokogiri::XML(open(game_location + '/eventLog.xml'))
43
+ players = Nokogiri::XML(open(game_location + '/players.xml'))
44
+ innings = Nokogiri::XML(open(game_location + '/inning/inning_all.xml'))
45
+
46
+ assert_equal 8, boxscore.search('pitcher').count
47
+ assert_equal 147, boxscore.search('boxscore').first.attribute('home_id').value.to_i
48
+ assert eventlog.search("event[number='19']").attribute('description').value.include?('Pedroia walks.')
49
+ assert_equal 'Magadan', players.search("team[type='away']").search("coach[position='batting_coach']").attribute('last').value
50
+ assert_equal 'Strikeout', innings.search('atbat').last.attribute('event').value
51
+ end
52
+
53
+ def test_pull_minor_league_games
54
+ Greenmonster::Spider.pull_day({:league => 'aaa', :print_games => false, :games_folder => @local_test_data_location, :date => Date.new(2011,9,1)})
55
+
56
+ assert_equal 13, Dir.entries(@local_test_data_location + '/aaa/year_2011/month_09/day_01/').count
57
+ %w(linescore.xml boxscore.xml players.xml eventLog.xml inning).each do |f|
58
+ assert Dir.entries(@local_test_data_location + '/aaa/year_2011/month_09/day_01/gid_2011_09_01_albaaa_mrbaaa_1/').include? f
59
+ end
60
+ end
61
+
62
+ def test_pull_games_prior_to_2008
63
+ Greenmonster::Spider.pull_day({:print_games => false, :games_folder => @local_test_data_location, :date => Date.new(2007,4,15)})
64
+
65
+ assert_equal 12, Dir.entries(@local_test_data_location + '/mlb/year_2007/month_04/day_15/gid_2007_04_15_detmlb_tormlb_1/inning/').count
66
+ end
67
+
68
+ def test_pull_days
69
+ Greenmonster::Spider.pull_days((Date.new(2011,8,4)..Date.new(2011,8,5)), {:print_games => false, :games_folder => @local_test_data_location})
70
+
71
+ assert_equal 4, Dir.entries(@local_test_data_location + '/mlb/year_2011/month_08/').count
72
+ assert_equal 17, Dir.entries(@local_test_data_location + '/mlb/year_2011/month_08/day_05').count
73
+ end
74
+
75
+ def teardown
76
+ FileUtils.remove_dir @local_test_data_location
77
+ end
78
+ end
metadata ADDED
@@ -0,0 +1,71 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: greenmonster
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0.pre
5
+ prerelease: 6
6
+ platform: ruby
7
+ authors:
8
+ - Geoff Harcourt
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-03-11 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: nokogiri
16
+ requirement: &70119326330320 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: 1.5.2
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: *70119326330320
25
+ - !ruby/object:Gem::Dependency
26
+ name: httparty
27
+ requirement: &70119326329200 !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ! '>='
31
+ - !ruby/object:Gem::Version
32
+ version: 0.8.1
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: *70119326329200
36
+ description: A utility for spidering and parsing MLB Gameday XML files.
37
+ email: geoff.harcourt@gmail.com
38
+ executables: []
39
+ extensions: []
40
+ extra_rdoc_files: []
41
+ files:
42
+ - Rakefile
43
+ - README.markdown
44
+ - lib/greenmonster/spider.rb
45
+ - lib/greenmonster.rb
46
+ - test/test_greenmonster.rb
47
+ homepage: http://rubygems.org/gems/greenmonster
48
+ licenses: []
49
+ post_install_message:
50
+ rdoc_options: []
51
+ require_paths:
52
+ - lib
53
+ required_ruby_version: !ruby/object:Gem::Requirement
54
+ none: false
55
+ requirements:
56
+ - - ! '>='
57
+ - !ruby/object:Gem::Version
58
+ version: '0'
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ none: false
61
+ requirements:
62
+ - - ! '>'
63
+ - !ruby/object:Gem::Version
64
+ version: 1.3.1
65
+ requirements: []
66
+ rubyforge_project:
67
+ rubygems_version: 1.8.11
68
+ signing_key:
69
+ specification_version: 3
70
+ summary: A utility for spidering and parsing MLB Gameday XML files.
71
+ test_files: []