Created
September 18, 2011 23:26
-
-
Save mattdennewitz/1225707 to your computer and use it in GitHub Desktop.
Calculate 2010 batting wOBA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from bson.code import Code | |
| import pymongo | |
| connection = pymongo.connection.Connection() | |
| db = connection['retrosheet'] | |
| tbl = db['events_2010'] | |
| # limit results to complete plate appearances. | |
| filters = {'PA_NEW_FL': 'T', 'PA_TRUNC_FL': 'F'} | |
| # map all plate appearances | |
| map_f = """ | |
| function() { | |
| var woba_fields = {nibb: (this.EVENT_CD == '14') ? 1 : 0, | |
| hbp: (this.EVENT_CD == '15') ? 1 : 0, | |
| _1b: (this.EVENT_CD == '20') ? 1 : 0, | |
| _2b: (this.EVENT_CD == '21') ? 1 : 0, | |
| _3b: (this.EVENT_CD == '22') ? 1 : 0, | |
| hr: (this.EVENT_CD == '23') ? 1 : 0, | |
| rboe: (this.BAT_SAFE_ERR_FL == 'T') ? 1 : 0, | |
| pa: 1}; | |
| emit(this.BAT_ID, woba_fields); | |
| } | |
| """ | |
| # tally wOBA components | |
| reduce_f = """ | |
| function(key, values) { | |
| var result = {nibb: 0, hbp: 0, _1b: 0, _2b: 0, _3b: 0, hr: 0, rboe: 0, pa: 0}; | |
| for(var i in values) { | |
| result.nibb += values[i].nibb; | |
| result.hbp += values[i].hbp; | |
| result._1b += values[i]._1b; | |
| result._2b += values[i]._2b; | |
| result._3b += values[i]._3b; | |
| result.hr += values[i].hr; | |
| result.rboe += values[i].rboe; | |
| result.pa += values[i].pa; | |
| } | |
| return result; | |
| } | |
| """ | |
| # calculate wOBA | |
| finalize_f = """ | |
| function(key, result) { | |
| return ((0.72 * result.nibb) + (0.75 * result.hbp) + (0.9 * result._1b) + (0.92 * result.rboe) + | |
| (1.24 * result._2b) + (1.56 * result._3b) + (1.95 * result.hr)) / result.pa; | |
| } | |
| """ | |
| # run wOBA map/reduce job, persisting results in a collection called "woba_2010". | |
| results = tbl.map_reduce(Code(map_f), Code(reduce_f), 'woba_2010', | |
| query=filters, | |
| finalize=Code(finalize_f)) | |
| for result in results.find(): | |
| print result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment