years.html


001| """Baseball Charts - All Team Years (Win%, Win-Loss, Run-Diff).
001| 
001| Functions:
001|     dispatch (cmd, **kwargs)                        ~module dispatch
001| 
001| Commands:
001|     500         do_franchise_500_chart              ~framchise year-by-year win percentage chart
001|     wl          do_franchise_win_loss_chart         ~franchise year-by-year wins and losses chart
001|     diff        do_franchise_run_diff_chart         ~franchise year-by-year run difference chart
001|     span        do_franchise_run_span_chart         ~franchise year-by-year run span (RS-RA) chart
001| 
001|     rank        do_franchise_seasons_ranking        ~franchise history explorer
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 matplotlib.pyplot as plt
007| import matplotlib.ticker as mltick
008| from logger import logger,info,debug,trace
009| from goodies import KWARG
010| import defs
011| ####################################################################################################
012| Log = logger('Years')
013| 
014| CMND = ''
015| ARGS = {
016|     #'team': 'twins',
017|     #'from': '1961',
018|     #'ymin': '500',
019|     #'fpath': defs.BasePath,
020| }
021| 
022| 
023| ##================================================================================================##
024| def do_franchise_500_chart (**kwargs):
025|     '''CMND: Create a chart of a franchise's above/below .500 year-by-year.'''
026|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
027|     fname = KWARG('fname', 'franchise-500-{tcode}.png', str, kwargs)
028|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
029|     year  = KWARG('from' , 0, int, kwargs)
030|     team_name = defs.MlbTeams[tcode][2]
031|     file_name = path.join(fpath,fname) if fpath else fname
032|     file_name = file_name.format(**locals())
033|     Log.info(f'franchise-500-chart:: {list(kwargs.keys())}')
034|     Log.debug(f'{fpath=}')
035|     Log.debug(f'{fname=}')
036|     Log.debug(f'{tcode=}')
037|     Log.debug(f'{year=}')
038|     Log.debug(f'{team_name=}')
039|     Log.debug(f'{file_name=}')
040|     Log.info()
041| 
042|     # Get team seasons data...
043|     csv_data = defs.CsvTeamSeasons(tcode)
044| 
045|     # Extract the columns of interest...
046|     years = csv_data.get_column_data_int('Year')
047|     win_pct = csv_data.get_column_data_float('W-L%')
048| 
049|     # Process data for chart...
050|     xs = []
051|     ys = []
052|     xmin,xmax = 5000, 0
053|     ymin,ymax = 0.300, 0.700
054| 
055|     for yr,wpct in zip(years, win_pct):
056|         if 0 < yr < year:
057|             continue
058|         if yr < xmin: xmin = yr
059|         if xmax < yr: xmax = yr
060|         xs.append(yr)
061|         ys.append(wpct)
062| 
063|     # Create a chart...
064|     fig, ax = plt.subplots()
065|     fig.set_figwidth(10.0)
066|     fig.set_figheight(4.0)
067|     fig.subplots_adjust(left=0.080, right=0.990, bottom=0.165, top=0.92)
068| 
069|     fig.suptitle(f'{team_name} Win/Loss Record {xmin}-{xmax}', fontsize=14, fontweight='bold')
070| 
071|     # Configure X-axis...
072|     ax.set_xlabel('Games', fontsize=12, fontweight='bold')
073|     ax.set_xlim(defs.RoundDown(xmin,5)-0.5, xmax+0.5)
074|     ax.xaxis.set_major_locator(mltick.MultipleLocator(5))
075|     ax.xaxis.set_minor_locator(mltick.MultipleLocator(1))
076|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
077| 
078|     for tick in ax.xaxis.get_major_ticks():
079|         tick.label1.set_rotation('vertical')
080|         tick.label1.set_size(9)
081| 
082|     # Configure Y-axis...
083|     ax.set_ylabel('Win %', fontsize=12, fontweight='bold')
084|     ax.set_ylim(ymin, ymax)
085|     ax.yaxis.set_major_locator(mltick.MultipleLocator(0.1))
086|     ax.yaxis.set_minor_locator(mltick.NullLocator())
087|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%.3f'))
088| 
089|     # Configure grid...
090|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
091|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
092|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
093|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
094| 
095|     # Plot data...
096|     ax.axhline(0.5, lw=3.0, color='#000000', alpha=0.75, zorder=10)
097|     ax.plot(xs,ys, color='#0000ff', lw=2.0, alpha=0.95, zorder=11)
098| 
099|     # Save the chart...
100|     fig.savefig(file_name)
101|     defs.prn(f'wrote: {file_name}')
102|     defs.prn()
103|     return file_name
104| 
105| ##================================================================================================##
106| def do_franchise_win_loss_chart (**kwargs):
107|     '''CMND: Create a chart of a franchise's run-diff year-by-year.'''
108|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
109|     fname = KWARG('fname', 'franchise-win-lose-{team}.png', str, kwargs)
110|     tcode = KWARG('team' , defs.TwinsCode, str, kwargs)
111|     year  = KWARG('from' , 0, int, kwargs)
112|     team_name = defs.MlbTeams[tcode][2]
113|     file_name = path.join(fpath,fname) if fpath else fname
114|     file_name = file_name.format(year=defs.DefaultYear, team=tcode)
115|     Log.info(f'franchise-win-lose-chart:: {list(kwargs.keys())}')
116|     Log.debug(f'{fpath=}')
117|     Log.debug(f'{fname=}')
118|     Log.debug(f'{tcode=}')
119|     Log.debug(f'{year=}')
120|     Log.debug(f'{team_name=}')
121|     Log.debug(f'{file_name=}')
122|     Log.info()
123| 
124|     # Get team seasons data...
125|     csv_data = defs.CsvTeamSeasons(tcode)
126| 
127|     # Extract the columns of interest...
128|     years = csv_data.get_column_data_int('Year')
129|     wins = csv_data.get_column_data_int('W')
130|     losses = csv_data.get_column_data_int('L')
131| 
132|     xs = []
133|     tops1, bots1 = [], []
134|     tops2, bots2 = [], []
135|     cs1 = []
136|     cs2 = []
137|     xmin,xmax = 5000, 0
138|     ymin,ymax = 0, 165
139|     for yr,nw,nl in zip(years, wins, losses):
140|         if 0 < yr < year:
141|             continue
142|         if yr < xmin: xmin = yr
143|         if xmax < yr: xmax = yr
144|         xs.append(yr)
145| 
146|         tops1.append(nw)
147|         bots1.append(0)
148|         tops2.append(nl)
149|         bots2.append(nw)
150| 
151|     # Create a chart...
152|     fig, ax = plt.subplots()
153|     fig.set_figwidth(10.0)
154|     fig.set_figheight(5.0)
155|     fig.subplots_adjust(left=0.065, right=0.990, bottom=0.145, top=0.92)
156| 
157|     fig.suptitle(f'{team_name} Win/Loss Record {xmin}-{xmax}', fontsize=14, fontweight='bold')
158| 
159|     # Configure X-axis...
160|     ax.set_xlabel('Year', fontsize=12, fontweight='bold')
161|     ax.set_xlim(defs.RoundDown(xmin,5)-0.5, xmax+0.5)
162|     ax.xaxis.set_major_locator(mltick.MultipleLocator(5))
163|     ax.xaxis.set_minor_locator(mltick.MultipleLocator(1))
164|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
165| 
166|     for tick in ax.xaxis.get_major_ticks():
167|         tick.label1.set_rotation('vertical')
168|         tick.label1.set_size(9)
169| 
170|     # Configure Y-axis...
171|     ax.set_ylabel('Games Won/Lost', fontsize=12, fontweight='bold')
172|     ax.set_ylim(ymin, ymax)
173|     ax.yaxis.set_major_locator(mltick.MultipleLocator(25))
174|     ax.yaxis.set_minor_locator(mltick.MultipleLocator(5))
175|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
176| 
177|     # Configure grid...
178|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
179|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
180|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
181|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
182| 
183|     # Plot data...
184|     ax.bar(xs, height=tops1, bottom=bots1, color='#1f3fbf', width=0.85, align='center', alpha=0.75, zorder=21)
185|     ax.bar(xs, height=tops2, bottom=bots2, color='#bf3f1f', width=0.85, align='center', alpha=0.75, zorder=21)
186| 
187|     # Save plot...
188|     fig.savefig(file_name)
189|     defs.prn(f'wrote: {file_name}')
190|     defs.prn()
191|     return file_name
192| 
193| ##================================================================================================##
194| def do_franchise_run_diff_chart (**kwargs):
195|     '''CMND: Create a chart of a franchise's run-difference year-by-year.'''
196|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
197|     fname = KWARG('fname', 'franchise-run-diff-{team}.png', str, kwargs)
198|     tcode = KWARG('team' , defs.TwinsCode, str, kwargs)
199|     year  = KWARG('from' , 0, int, kwargs)
200|     team_name = defs.MlbTeams[tcode][2]
201|     file_name = path.join(fpath,fname) if fpath else fname
202|     file_name = file_name.format(year=defs.DefaultYear, team=tcode)
203|     Log.info(f'franchise-run-diff-chart:: {list(kwargs.keys())}')
204|     Log.debug(f'{fpath=}')
205|     Log.debug(f'{fname=}')
206|     Log.debug(f'{tcode=}')
207|     Log.debug(f'{year=}')
208|     Log.debug(f'{team_name=}')
209|     Log.debug(f'{file_name=}')
210|     Log.info()
211| 
212|     # Get team seasons data...
213|     csv_data = defs.CsvTeamSeasons(tcode)
214| 
215|     # Extract the columns of interest...
216|     years = csv_data.get_column_data_int('Year')
217|     runs_scored = csv_data.get_column_data_int('R')
218|     runs_allowed = csv_data.get_column_data_int('RA')
219| 
220|     xs = []
221|     ys = []
222|     cs = []
223|     xmin,xmax = 5000, 0
224|     for yr,rs,ra in zip(years, runs_scored, runs_allowed):
225|         if 0 < yr < year:
226|             continue
227|         if yr < xmin: xmin = yr
228|         if xmax < yr: xmax = yr
229|         dif = rs - ra
230|         xs.append(yr)
231|         ys.append(dif)
232|         cs.append('red' if dif<0 else 'green')
233| 
234|     ymax = defs.RoundUp(max(ys), 100)
235|     ymin = defs.RoundDown(min(ys), 100)
236| 
237|     for x,y,c in zip(xs,ys,cs):
238|         Log.trace(f'{x=}, {y=}, {c=}')
239|     Log.trace()
240| 
241|     # Create a chart...
242|     fig, ax = plt.subplots()
243|     fig.set_figwidth(10.0)
244|     fig.set_figheight(5.0)
245|     fig.subplots_adjust(left=0.075, right=0.990, bottom=0.145, top=0.92)
246| 
247|     fig.suptitle(f'{team_name} Runs Differential Record {xmin}-{xmax}', fontsize=14, fontweight='bold')
248| 
249|     # Configure X-axis...
250|     ax.set_xlabel('Year', fontsize=12, fontweight='bold')
251|     ax.set_xlim(defs.RoundDown(xmin,5)-0.5, xmax+0.5)
252|     ax.xaxis.set_major_locator(mltick.MultipleLocator(5))
253|     ax.xaxis.set_minor_locator(mltick.MultipleLocator(1))
254|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
255| 
256|     for tick in ax.xaxis.get_major_ticks():
257|         tick.label1.set_rotation('vertical')
258|         tick.label1.set_size(9)
259| 
260|     # Configure Y-axis...
261|     ax.set_ylabel('Runs', fontsize=12, fontweight='bold')
262|     ax.set_ylim(ymin, ymax)
263|     ax.yaxis.set_major_locator(mltick.MultipleLocator(100))
264|     ax.yaxis.set_minor_locator(mltick.MultipleLocator(10))
265|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%+d'))
266| 
267|     # Configure grid...
268|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
269|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
270|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
271|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
272| 
273|     # Plot data...
274|     ax.axhline(0.0, lw=1.7, color='#000000', alpha=0.75, zorder=11)
275|     ax.bar(xs,ys, color=cs, width=1.00, align='center', alpha=0.75, zorder=21)
276| 
277|     # Save plot...
278|     fig.savefig(file_name)
279|     defs.prn(f'wrote: {file_name}')
280|     defs.prn()
281|     return file_name
282| 
283| ##================================================================================================##
284| def do_franchise_run_span_chart (**kwargs):
285|     '''CMND: Create a chart of a franchise's run-span year-by-year.'''
286|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
287|     fname = KWARG('fname', 'franchise-run-span-{team}.png', str, kwargs)
288|     tcode = KWARG('team' , defs.TwinsCode, str, kwargs)
289|     year  = KWARG('from' , 0, int, kwargs)
290|     ybot  = KWARG('ymin' , -1, int, kwargs)
291|     team_name = defs.MlbTeams[tcode][2]
292|     file_name = path.join(fpath,fname) if fpath else fname
293|     file_name = file_name.format(year=defs.DefaultYear, team=tcode)
294|     Log.info(f'franchise-run-span-chart:: {list(kwargs.keys())}')
295|     Log.debug(f'{fpath=}')
296|     Log.debug(f'{fname=}')
297|     Log.debug(f'{tcode=}')
298|     Log.debug(f'{year=}')
299|     Log.debug(f'{ybot=}')
300|     Log.debug(f'{team_name=}')
301|     Log.debug(f'{file_name=}')
302|     Log.info()
303| 
304|     # Get team seasons data...
305|     csv_data = defs.CsvTeamSeasons(tcode)
306| 
307|     # Extract the columns of interest...
308|     years = csv_data.get_column_data_int('Year')
309|     runs_scored = csv_data.get_column_data_int('R')
310|     runs_allowed = csv_data.get_column_data_int('RA')
311| 
312|     xs  = []
313|     ys1 = []
314|     ys2 = []
315|     cs  = []
316|     xmin,xmax = 5000, 0
317|     ymin,ymax = 5000, 0
318|     for yr,rs,ra in zip(years, runs_scored, runs_allowed):
319|         if 0 < yr < year:
320|             continue
321|         if yr < xmin: xmin = yr
322|         if xmax < yr: xmax = yr
323|         high = max(rs,ra)
324|         low = min(rs,ra)
325|         dif = rs - ra
326|         if low < ymin: ymin = low
327|         if ymax < high: ymax = high
328|         xs.append(yr)
329|         ys1.append(abs(dif))
330|         ys2.append(low)
331|         cs.append('red' if dif<0 else 'green')
332| 
333|     if 0 <= ybot: ymin = ybot
334| 
335|     for datum in zip(xs,ys1,ys2,cs):
336|         Log.trace(datum)
337|     Log.trace()
338| 
339|     # Create a chart...
340|     fig, ax = plt.subplots()
341|     fig.set_figwidth(10.0)
342|     fig.set_figheight(5.0)
343|     fig.subplots_adjust(left=0.075, right=0.990, bottom=0.145, top=0.92)
344| 
345|     fig.suptitle(f'{team_name} Runs Scored/Allowed Record {xmin}-{xmax}', fontsize=14, fontweight='bold')
346| 
347|     # Configure X-axis...
348|     ax.set_xlabel('Year', fontsize=12, fontweight='bold')
349|     ax.set_xlim(defs.RoundDown(xmin,5)-0.5, xmax+0.5)
350|     ax.xaxis.set_major_locator(mltick.MultipleLocator(5))
351|     ax.xaxis.set_minor_locator(mltick.MultipleLocator(1))
352|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
353| 
354|     for tick in ax.xaxis.get_major_ticks():
355|         tick.label1.set_rotation('vertical')
356|         tick.label1.set_size(9)
357| 
358|     # Configure Y-axis...
359|     ax.set_ylabel('Runs Scored/Runs Allowed', fontsize=12, fontweight='bold')
360|     ax.set_ylim(defs.RoundDown(ymin,100), defs.RoundUp(ymax,100))
361|     ax.yaxis.set_major_locator(mltick.MultipleLocator(100))
362|     ax.yaxis.set_minor_locator(mltick.MultipleLocator(10))
363|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
364| 
365|     # Configure grid...
366|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
367|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
368|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
369|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
370| 
371|     # Plot data...
372|     ax.bar(xs, height=ys1, bottom=ys2, color=cs, width=1.00, align='center', alpha=0.75, zorder=21)
373| 
374|     # Save plot...
375|     fig.savefig(file_name)
376|     defs.prn(f'wrote: {file_name}')
377|     defs.prn()
378|     return file_name
379| 
380| ##================================================================================================##
381| def do_franchise_seasons_ranking (**kwargs):
382|     '''CMND: Franchise Years Scanner.'''
383|     fpath = KWARG('fpath', defs.ListPath, str, kwargs)
384|     fname = KWARG('fname', '{team}-history.out', str, kwargs)
385|     tcode = KWARG('team' , defs.TwinsCode, str, kwargs)
386|     file_name = path.join(fpath,fname) if fpath else fname
387|     file_name = file_name.format(team=tcode)
388|     Log.info(f'franchise-history:: {list(kwargs.keys())}')
389|     Log.debug(f'{fpath=}')
390|     Log.debug(f'{fname=}')
391|     Log.debug(f'{tcode=}')
392|     Log.debug(f'{file_name=}')
393|     Log.info()
394| 
395|     win_pct = lambda w,l: f'{w/(w+l):.3f}'[1:]
396|     sort_key = lambda t: (t[1] / (t[1] + t[2]))
397| 
398|     # Load the CSV data...
399|     csv_data = defs.CsvTeamSeasons(tcode)
400|     team_name = defs.MlbTeams[tcode][2]
401|     team_city = defs.MlbTeams[tcode][3]
402| 
403|     # Extract the columns of interest...
404|     years = csv_data.get_column_data_int('Year')
405|     won   = csv_data.get_column_data_int('W')
406|     lost  = csv_data.get_column_data_int('L')
407| 
408|     # Sort data by win percentage...
409|     props = dict(key=sort_key, reverse=True)
410|     data = [t for t in sorted(zip(years,won,lost), **props) if 1960 < t[0]]
411| 
412|     # List the results...
413|     defs.prn(f'{team_city} {team_name} Seasons Ranking')
414|     defs.prn()
415|     wins,losses = 0,0
416|     for ix,t in enumerate(data, start=1):
417|         y,w,l = t
418|         wins += w
419|         losses += l
420|         defs.prn(f'[{ix:2d}] {y} {w:3d}-{l:3d} ({win_pct(w,l)})')
421|     defs.prn()
422|     defs.prn(f'Overall: {wins}-{losses} ({win_pct(wins,losses)})')
423|     defs.prn()
424| 
425|     return file_name
426| 
427| ##================================================================================================##
428| def do_test (**kwargs):
429|     '''CMND: Do a test.'''
430|     fpath = KWARG('fpath', defs.BasePath, str, kwargs)
431|     fname = KWARG('fname', 'test-{tcode}-{year}.png', str, kwargs)
432|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
433|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
434|     team_name = defs.MlbTeams[tcode][2]
435|     file_name = path.join(fpath,fname) if fpath else fname
436|     file_name = file_name.format(**locals())
437|     Log.info(f'test:: {list(kwargs.keys())}')
438|     Log.debug(f'{fpath=}')
439|     Log.debug(f'{fname=}')
440|     Log.debug(f'{tcode=}')
441|     Log.debug(f'{year=}')
442|     Log.debug(f'{team_name=}')
443|     Log.debug(f'{file_name=}')
444|     Log.info()
445| 
446|     # extract data from team's season...
447|     csv_data = defs.CsvTeamGames(tcode)
448| 
449|     Log.info()
450|     return file_name
451| 
452| ####################################################################################################
453| def dispatch (cmd, **kwargs):
454|     '''Dispatch to a module function based on CMD.'''
455|     Log.info(f'CMD: {cmd}')
456|     for kw in kwargs:
457|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
458|     Log.info()
459| 
460|     if cmd == '500':  return do_franchise_500_chart         (**kwargs)
461|     if cmd == 'wl':   return do_franchise_win_loss_chart    (**kwargs)
462|     if cmd == 'diff': return do_franchise_run_diff_chart    (**kwargs)
463|     if cmd == 'span': return do_franchise_run_span_chart    (**kwargs)
464|     if cmd == 'rank': return do_franchise_seasons_ranking   (**kwargs)
465|     if cmd == 'test': return do_test                        (**kwargs)
466| 
467|     return 'Nothing to do!'
468| ####################################################################################################
469| if __name__ == '__main__':
470|     print(f'autorun: {argv[0]}')
471|     Log.start(path.join(defs.BasePath,'years.log'))
472|     Log.level(trace())
473|     Log.info(argv[0])
474|     cmd = argv[1] if 1 < len(argv) else CMND
475|     kwargs = ARGS
476|     for a in argv[2:]:
477|         nv = a.split('=', 1)
478|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
479|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
480|     Log.info()
481|     try:
482|         print(f'CMD: {cmd}')
483|         print()
484|         obj = dispatch(cmd, **kwargs)
485|         print(obj)
486|         print()
487|         Log.info(obj)
488|         Log.info()
489|     except:
490|         etype, evalue, tb = exc_info()
491|         ts = extract_tb(tb)
492|         Log.error()
493|         Log.error(f'{etype.__name__}: {evalue!s}')
494|         Log.error()
495|         for t in ts[-5:]:
496|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
497|             Log.error(f' {t[3]}')
498|             Log.error()
499|         raise
500|     finally:
501|         Log.end()
502| ####################################################################################################
503| '''eof'''
504|