twins.html
001| """Baseball Charts - TWins (Win/Loss Record; Managers; Batting & Pitching).
001|
001| Commands:
001| wlrec do_twins_win_loss_history ~Twins All Seasons Win/Loss Chart
001| bat do_twins_batting ~Twins Season Batting Chart
001| pit do_twins_pitching ~Twins Season Pitching Chart
001| mgrs do_twins_managers ~Stats on Twins managers...
001| test do_test ~test
001|
001| """
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| import datetime as dttm
007| import matplotlib.pyplot as plt
008| import matplotlib.ticker as mltick
009| import matplotlib.dates as mldate
010| import matplotlib.patches as mlpatch
011| from logger import logger,info,debug,trace
012| from goodies import KWARG, marker
013| import defs
014|
015| Log = logger('Twins')
016|
017| CMND = ''
018| ARGS = {
019|
020|
021|
022| }
023|
024|
025|
026| Managers = {
027| 'before Kelly': [1961, 1986, 0, 0, 0.0],
028| 'Tom Kelly': [1987, 2001, 0, 0, 0.0],
029| 'Ron Gardenhire': [2002, 2014, 0, 0, 0.0],
030| 'Paul Molitor': [2015, 2018, 0, 0, 0.0],
031| 'Rocco Baldelli': [2019, 2025, 0, 0, 0.0],
032| 'Derek Shelton': [2026, 2026, 0, 0, 0.0],
033| }
034|
035|
036| CalculatePercentage = lambda ns,m: (sum(ns)/m)*100.0
037|
038|
039|
040| def do_twins_win_loss_history (**kwargs):
041| '''CMND: Create a Twins win/loss history chart.'''
042| fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
043| fname = KWARG('fname', 'twins-win-loss.png', str, kwargs)
044| Log.info(f'twins-win-loss-history-chart:: {list(kwargs.keys())}')
045| Log.debug(f'{fpath=}')
046| Log.debug(f'{fname=}')
047| Log.info()
048| color_mn = (defs.TwinsBlue, '#000000')
049| color_ws = ('#ff3300', '#660000')
050| color_cs = ('#ffff00', '#999900')
051| color_ds = ('#33ff33', '#009900')
052| color_wc = ('#ff00ff', '#990099')
053| filename = path.join(fpath,fname) if fpath else fname
054| filename = filename.format(year=defs.DefaultYear)
055|
056| def colorize (txt):
057| Log.trace(f'colorize({txt})')
058| if len(txt) == 0:
059| return color_mn[0]
060| if 'WS' in txt:
061| if txt.startswith('Won'):
062| return color_ws[0]
063| return color_ws[1]
064| if 'CS' in txt:
065| if txt.startswith('Won'):
066| return color_cs[0]
067| return color_cs[1]
068| if 'DS' in txt:
069| if txt.startswith('Won'):
070| return color_ds[0]
071| return color_ds[1]
072| if 'WC' in txt:
073| if txt.startswith('Won'):
074| return color_wc[0]
075| return color_wc[1]
076| return color_mn[1]
077|
078| csv_data = defs.CsvTeamSeasons(defs.TwinsCode)
079| years = csv_data.get_column_data_int('Year')
080| won = csv_data.get_column_data_int('W')
081| lost = csv_data.get_column_data_int('L')
082| pct = csv_data.get_column_data_float('W-L%')
083| post = csv_data.get_column_data('Playoffs')
084|
085| for ix,yr,w,l,pct in zip(marker(),years,won,lost,pct):
086| Log.info(f'{ix:3.0f}: {yr} {w:3d}-{l:3d} ({pct:.3f}) [{pct-(w/(w+l)):+.3f}]')
087| Log.info()
088|
089| xs = [y for y in reversed(years) if 1960 < y]
090| ys = [w/(w+l) for _,w,l in reversed(list(zip(xs,won,lost)))]
091| cs = [colorize(p) for _,p in reversed(list(zip(xs,post)))]
092|
093|
094| cs[xs.index(1981)] = '#3f3f3f'
095| cs[xs.index(1982)] = '#3f3f3f'
096| cs[xs.index(2016)] = '#000000'
097|
098| Log.debug(xs)
099| Log.debug(ys)
100| Log.debug(cs)
101|
102|
103| fig, ax = plt.subplots()
104| fig.set_figwidth(10.0)
105| fig.set_figheight(5.0)
106| fig.subplots_adjust(left=0.080, right=0.990, bottom=0.14, top=0.93)
107|
108| fig.suptitle(f'Twins Win/Loss Record 1961-{defs.DefaultYear}', fontsize=14, fontweight='bold')
109|
110|
111| ax.set_xlabel('Year', fontsize=12, fontweight='bold')
112| ax.set_xlim(1960, defs.DefaultYear+1)
113| ax.xaxis.set_major_locator(mltick.MultipleLocator(5))
114| ax.xaxis.set_minor_locator(mltick.MultipleLocator(1))
115| ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
116|
117| for tick in ax.xaxis.get_major_ticks():
118| tick.label1.set_rotation('vertical')
119| tick.label1.set_size(9)
120|
121|
122| ax.set_ylabel('Win Percentage', fontsize=12, fontweight='bold')
123| ax.set_ylim(0.300, 0.700)
124| ax.yaxis.set_major_locator(mltick.MultipleLocator(0.1))
125| ax.yaxis.set_minor_locator(mltick.MultipleLocator(0.01))
126| ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%.3f'))
127|
128|
129| ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
130| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
131| ax.tick_params(which='major', axis='both', direction='out', color='#000000')
132| ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
133|
134|
135| ax.axhline(0.5, lw=1.7, color='#000000', alpha=1.00, zorder=10)
136| ax.bar(xs,ys, width=0.70, color=cs, edgecolor='#000000', lw=0.5, alpha=0.85, zorder=11)
137|
138|
139| patchs = [
140| mlpatch.Patch(facecolor=color_ws[0], edgecolor='#000000', lw=0.75),
141| mlpatch.Patch(facecolor=color_ws[1], edgecolor='#000000', lw=0.75),
142| mlpatch.Patch(facecolor=color_cs[1], edgecolor='#000000', lw=0.75),
143| mlpatch.Patch(facecolor=color_ds[1], edgecolor='#000000', lw=0.75),
144| mlpatch.Patch(facecolor=color_wc[1], edgecolor='#000000', lw=0.75),
145| ]
146| labels = ['Won WS', 'Lost WS', 'Lost ALCS', 'Lost ALDS', 'Lost ALWC']
147| fig.legend(patchs, labels, loc='upper right', ncols=5, fontsize=10, bbox_to_anchor=(0.99,0.93))
148|
149|
150| fig.savefig(filename)
151| defs.prn(f'wrote: {filename}')
152| defs.prn()
153|
154| return filename
155|
156|
157| def do_twins_batting (**kwargs):
158| '''CMND: Twins Season Batting.'''
159| fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
160| fname = KWARG('fname', 'twins-batting-{year}.png', str, kwargs)
161| window = KWARG('window', 10, int, kwargs)
162| Log.info(f'twins-batting-{defs.DefaultYear}:: {list(kwargs.keys())}')
163| Log.debug(f'{fpath=}')
164| Log.debug(f'{fname=}')
165| Log.debug(f'{window=}')
166| Log.info()
167| filename = path.join(fpath,fname) if fpath else fname
168| filename = filename.format(year=defs.DefaultYear)
169|
170| csv_data = defs.CsvTeamGamesBatting()
171| del csv_data.data[-1]
172|
173| data_dt = csv_data.get_column_data_date('Date')
174| data_pa = csv_data.get_column_data_int('PA')
175| data_h = csv_data.get_column_data_int('H')
176| data_r = csv_data.get_column_data_int('R')
177| data_hr = csv_data.get_column_data_int('HR')
178| data_so = csv_data.get_column_data_int('SO')
179| data_bb = csv_data.get_column_data_int('BB')
180|
181| xmin = data_dt[0] - dttm.timedelta(1)
182| xmax = data_dt[-1] + dttm.timedelta(1)
183|
184| tot_pa = sum(data_pa)
185| tot_h = sum(data_h)
186| tot_r = sum(data_r)
187| tot_bb = sum(data_bb)
188| tot_so = sum(data_so)
189| tot_hr = sum(data_hr)
190| Log.info(f'Overall,N: {tot_pa} PA, {tot_h} H, {tot_r} R, {tot_bb} BB, {tot_so} SO, {tot_hr} HR')
191| Log.info(f'Overall,%: {100*(tot_h/tot_pa):.1f}% H, {100*(tot_r/tot_pa):.1f}% R, {100*(tot_bb/tot_pa):.1f}% BB, {100*(tot_so/tot_pa):.1f}% SO, {100*(tot_hr/tot_pa):.1f}% HR')
192| Log.info()
193|
194| buf_pa = defs.ringbuff([], window)
195| buf_h = defs.ringbuff([], window)
196| buf_r = defs.ringbuff([], window)
197| buf_bb = defs.ringbuff([], window)
198| buf_so = defs.ringbuff([], window)
199| buf_hr = defs.ringbuff([], window)
200|
201| h_pct,r_pct,bb_pct,so_pct,hr_pct = [],[],[],[],[]
202| for dt,pa,h,r,hr,so,bb in zip(data_dt, data_pa, data_h, data_r, data_hr, data_so, data_bb):
203| Log.debug(f'{dt:%M-%D}, {pa=}, {h=}, {r=}, {bb=}, {so=}')
204|
205|
206| buf_p.put(pa)
207| buf_h.put(h)
208| buf_r.put(r)
209| buf_bb.put(bb)
210| buf_so.put(so)
211| buf_hr.put(hr)
212|
213|
214| tot_pa = sum(buf_pa)
215| h_pct.append(CalculatePercentage(buf_h,tot_pa))
216| r_pct.append(CalculatePercentage(buf_r,tot_pa))
217| bb_pct.append(CalculatePercentage(buf_bb,tot_pa))
218| so_pct.append(CalculatePercentage(buf_so,tot_pa))
219| hr_pct.append(CalculatePercentage(buf_so,tot_pa))
220|
221| Log.debug()
222| Log.debug(h_pct)
223| Log.debug(r_pct)
224| Log.debug(bb_pct)
225| Log.debug(so_pct)
226| Log.debug(hr_pct)
227| Log.debug()
228|
229|
230| fig, ax = plt.subplots()
231| fig.set_figwidth(10.0)
232| fig.set_figheight(4.0)
233| fig.subplots_adjust(left=0.065, right=0.990, bottom=0.13, top=0.91)
234|
235| fig.suptitle(f'Twins {defs.DefaultYear} - Batting ({window} game window)', fontsize=15, fontweight='bold')
236|
237|
238| ax.set_xlabel('Date', fontsize=12, fontweight='bold')
239| ax.xaxis_date()
240| ax.set_xlim(xmin, xmax)
241| ax.xaxis.set_major_locator(mldate.MonthLocator())
242| ax.xaxis.set_minor_locator(mldate.DayLocator(bymonthday=[8,15,22]))
243| ax.xaxis.set_major_formatter(mldate.DateFormatter('%b'))
244|
245|
246| ax.set_ylabel('Percentage', fontsize=10, fontweight='bold')
247| ax.set_ylim(0.0, 30.0)
248| ax.yaxis.set_major_locator(mltick.MultipleLocator(10.0))
249| ax.yaxis.set_minor_locator(mltick.MultipleLocator(2.0))
250| ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%.0f%%'))
251|
252|
253| ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
254| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
255| ax.tick_params(which='major', axis='both', direction='out', color='#000000')
256| ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
257|
258|
259| ax.plot(data_dt, h_pct , label='H%' , c='#4f4f00', lw=2.5, alpha=0.8, zorder=14)
260| ax.plot(data_dt, r_pct , label='R%' , c='#0faf1f', lw=2.5, alpha=0.8, zorder=13)
261| ax.plot(data_dt, hr_pct, label='HR%', c='#bf9f00', lw=2.5, alpha=0.8, zorder=10)
262| ax.plot(data_dt, bb_pct, label='BB%', c='#5f006f', lw=2.5, alpha=0.8, zorder=12)
263| ax.plot(data_dt, so_pct, label='SO%', c='#ff0000', lw=2.5, alpha=0.8, zorder=11)
264|
265|
266| fig.legend(loc='upper left', ncols=5, fontsize=10, bbox_to_anchor=(0.400,0.920))
267|
268|
269| fig.savefig(filename)
270| defs.prn(f'wrote: {filename}')
271| defs.prn()
272| return filename
273|
274|
275| def do_twins_pitching (**kwargs):
276| '''CMND: Twins Season Pitching.'''
277| fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
278| fname = KWARG('fname', 'twins-pitching-{year}.png', str, kwargs)
279| window = KWARG('fname', 10, int, kwargs)
280| Log.info(f'twins-pitching-{defs.DefaultYear}:: {list(kwargs.keys())}')
281| Log.debug(f'{fpath=}')
282| Log.debug(f'{fname=}')
283| Log.debug(f'{window=}')
284| Log.info()
285| filename = path.join(fpath,fname) if fpath else fname
286| filename = filename.format(year=defs.DefaultYear)
287|
288| csv_data = defs.CsvTeamGamesPitching()
289| del csv_data.data[-1]
290|
291| data_dt = csv_data.get_column_data_date('Date')
292| data_ip = csv_data.get_column_data('IP')
293| data_bf = csv_data.get_column_data_int('BF')
294| data_h = csv_data.get_column_data_int('H')
295| data_er = csv_data.get_column_data_int('ER')
296| data_hr = csv_data.get_column_data_int('HR')
297| data_so = csv_data.get_column_data_int('SO')
298| data_bb = csv_data.get_column_data_int('BB')
299|
300| xmin = data_dt[0] - dttm.timedelta(1)
301| xmax = data_dt[-1] + dttm.timedelta(1)
302|
303| tot_bf = sum(data_bf)
304| tot_h = sum(data_h)
305| tot_er = sum(data_er)
306| tot_hr = sum(data_hr)
307| tot_bb = sum(data_bb)
308| tot_so = sum(data_so)
309| Log.info(f'Overall,N: {tot_bf} BF, {tot_h} H, {tot_er} ER, {tot_hr} HR, {tot_bb} BB, {tot_so} SO')
310| Log.info(f'Overall,%: {100*(tot_h/tot_bf):.1f}% H, {100*(tot_er/tot_bf):.1f}% ER, {100*(tot_hr/tot_bf):.1f}% HR, {100*(tot_bb/tot_bf):.1f}% BB, {100*(tot_so/tot_bf):.1f}% SO')
311| Log.info()
312|
313| buf_bf = defs.ringbuff([], window)
314| buf_h = defs.ringbuff([], window)
315| buf_er = defs.ringbuff([], window)
316| buf_hr = defs.ringbuff([], window)
317| buf_bb = defs.ringbuff([], window)
318| buf_so = defs.ringbuff([], window)
319|
320| er_pct,h_pct,hr_pct,bb_pct,so_pct = [],[],[],[],[]
321| for dt,ip,bf,h,er,hr,so,bb in zip(data_dt, data_ip, data_bf, data_h, data_er, data_hr, data_so, data_bb):
322| Log.debug(f'{dt:%M-%D}, {ip=}, {bf=}, {h=}, {er=}, {hr=}, {bb=}, {so=}')
323|
324|
325| buf_bf.put(bf)
326| buf_h.put(h)
327| buf_er.put(er)
328| buf_hr.put(hr)
329| buf_bb.put(bb)
330| buf_so.put(so)
331|
332|
333| tot_bf = sum(buf_bf)
334| h_pct.append(CalculatePercentage(buf_h,tot_bf))
335| er_pct.append(CalculatePercentage(buf_er,tot_bf))
336| hr_pct.append(CalculatePercentage(buf_hr,tot_bf))
337| bb_pct.append(CalculatePercentage(buf_bb,tot_bf))
338| so_pct.append(CalculatePercentage(buf_so,tot_bf))
339|
340| Log.debug()
341| Log.debug(h_pct)
342| Log.debug(er_pct)
343| Log.debug(hr_pct)
344| Log.debug(bb_pct)
345| Log.debug(so_pct)
346| Log.debug()
347|
348|
349| fig, ax = plt.subplots()
350| fig.set_figwidth(10.0)
351| fig.set_figheight(4.0)
352| fig.subplots_adjust(left=0.065, right=0.990, bottom=0.13, top=0.91)
353|
354| fig.suptitle(f'Twins {defs.DefaultYear} - Pitching ({window} game window)', fontsize=15, fontweight='bold')
355|
356|
357| ax.set_xlabel('Date', fontsize=12, fontweight='bold')
358| ax.xaxis_date()
359| ax.set_xlim(xmin, xmax)
360| ax.xaxis.set_major_locator(mldate.MonthLocator())
361| ax.xaxis.set_minor_locator(mldate.DayLocator(bymonthday=[8,15,22]))
362| ax.xaxis.set_major_formatter(mldate.DateFormatter('%b'))
363|
364|
365| ax.set_ylabel('Percentage', fontsize=10, fontweight='bold')
366| ax.set_ylim(0.0, 30.0)
367| ax.yaxis.set_major_locator(mltick.MultipleLocator(10.0))
368| ax.yaxis.set_minor_locator(mltick.MultipleLocator(2.0))
369| ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%.0f%%'))
370|
371|
372| ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
373| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
374| ax.tick_params(which='major', axis='both', direction='out', color='#000000')
375| ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
376|
377|
378| ax.plot(data_dt, h_pct , label='H%' , c='#4f4f00', lw=2.5, alpha=0.8, zorder=15)
379| ax.plot(data_dt, er_pct, label='ER%', c='#0faf1f', lw=2.5, alpha=0.8, zorder=14)
380| ax.plot(data_dt, bb_pct, label='BB%', c='#5f006f', lw=2.5, alpha=0.8, zorder=12)
381| ax.plot(data_dt, so_pct, label='SO%', c='#ff0000', lw=2.5, alpha=0.8, zorder=11)
382| ax.plot(data_dt, hr_pct, label='HR%', c='#bf9f00', lw=2.5, alpha=0.8, zorder=13)
383|
384|
385| fig.legend(loc='upper left', ncols=5, fontsize=10, bbox_to_anchor=(0.350,0.920))
386|
387|
388| fig.savefig(filename)
389| defs.prn(f'wrote: {filename}')
390| defs.prn()
391| return filename
392|
393|
394| def do_twins_managers (**kwargs):
395| '''CMND: Create some stats related to Twins managers.'''
396| fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
397| fname = KWARG('fname', 'managers.out', str, kwargs)
398| Log.info(f'twins-managers:: {list(kwargs.keys())}')
399| Log.debug(f'{fpath=}')
400| Log.debug(f'{fname=}')
401| Log.info()
402| filename = path.join(fpath,fname) if fpath else fname
403|
404|
405| csv_data = defs.CsvTeamSeasons(defs.TwinsCode)
406| years = csv_data.get_column_data_int('Year', reverse=True)
407| won = csv_data.get_column_data_int('W', reverse=True)
408| lost = csv_data.get_column_data_int('L', reverse=True)
409|
410| records = [t for t in zip(years,won,lost) if 1961 <= t[0]]
411|
412| for ix,t in enumerate(records, start=1):
413| yr,w,l = t
414| defs.prn(f'{ix:3.0f}: {yr} {w:3d}-{l:3d} [{w/(w+l):+.3f}]')
415|
416| for rcd in Managers.values():
417| if rcd[0] <= yr <= rcd[1]:
418| rcd[2] += w
419| rcd[3] += l
420| defs.prn()
421|
422| col_width = 0
423| for name in Managers:
424| if col_width < len(name):
425| col_width = len(name)
426|
427| for mgr in Managers:
428| stats = Managers[mgr]
429| tot = stats[2] + stats[3]
430| pct = float(stats[2]) / float(tot)
431| defs.prn(f'{mgr:<{col_width}s} ({stats[0]}-{stats[1]}): {stats[2]:4d}-{stats[3]:4d} [{pct:.3f}] ({tot:4d} games)')
432| defs.prn()
433|
434| Log.info()
435| return 'Done'
436|
437|
438| def do_test (**kwargs):
439| '''CMND: Do a test.'''
440| fpath = KWARG('fpath', defs.BasePath, str, kwargs)
441| fname = KWARG('fname', 'test-{tcode}-{year}.png', str, kwargs)
442| tcode = KWARG('team', defs.TwinsCode, str, kwargs)
443| year = KWARG('year', defs.DefaultYear, int, kwargs)
444| team_name = defs.MlbTeams[tcode][2]
445| file_name = path.join(fpath,fname) if fpath else fname
446| file_name = file_name.format(**locals())
447| Log.info(f'test:: {list(kwargs.keys())}')
448| Log.debug(f'{fpath=}')
449| Log.debug(f'{fname=}')
450| Log.debug(f'{tcode=}')
451| Log.debug(f'{year=}')
452| Log.debug(f'{team_name=}')
453| Log.debug(f'{file_name=}')
454| Log.info()
455|
456|
457| csv_data = defs.CsvTeamGames(tcode)
458|
459| Log.info()
460| return file_name
461|
462|
463| def dispatch (cmd, **kwargs):
464| '''Dispatch to a module function based on CMD.'''
465| Log.info(f'CMD: {cmd}')
466| for kw in kwargs:
467| Log.debug(f'argument[{kw}]: {kwargs[kw]}')
468| Log.info()
469|
470| if cmd == 'wlrec': return do_twins_win_loss_history (**kwargs)
471| if cmd == 'bat': return do_twins_batting (**kwargs)
472| if cmd == 'pit': return do_twins_pitching (**kwargs)
473| if cmd == 'mgrs': return do_twins_managers (**kwargs)
474| if cmd == 'test': return do_test (**kwargs)
475|
476| return 'Nothing to do!'
477|
478| if __name__ == '__main__':
479| print(f'autorun: {argv[0]}')
480| Log.start(path.join(defs.BasePath,'twins.log'))
481| Log.level(trace())
482| Log.info(argv[0])
483| cmd = argv[1] if 1 < len(argv) else CMND
484| kwargs = ARGS
485| for a in argv[2:]:
486| nv = a.split('=', 1)
487| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
488| Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
489| Log.info()
490| try:
491| print(f'CMD: {cmd}')
492| print()
493| obj = dispatch(cmd, **kwargs)
494| print(obj)
495| print()
496| Log.info(obj)
497| Log.info()
498| except:
499| etype, evalue, tb = exc_info()
500| ts = extract_tb(tb)
501| Log.error()
502| Log.error(f'{etype.__name__}: {evalue!s}')
503| Log.error()
504| for t in ts[-5:]:
505| Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
506| Log.error(f' {t[3]}')
507| Log.error()
508| raise
509| finally:
510| Log.end()
511|
512| '''eof'''
513|