season.html


001| """Baseball Charts - Season Division, League, and MLB; plus Team Win% and Monthly Win%.
001| 
001| Classes:
001|     parameters (dict)                   ~specialized dictionary for create_chart
001| 
001| Functions:
001|     create_chart (func, **kw)           ~generate a wins over games chart
001|     dispatch (cmd, **kw)                ~module dispatch function
001| 
001| Commands:
001|     div         do_division_wins_chart              ~win progress of all teams in division.
001|     lea         do_league_wins_chart                ~win progress of all teams in league.
001|     mlb         do_mlb_wins_chart                   ~win progress of all teams in MLB.
001| 
001|     500         do_season_500_chart                 ~team season win percentage chart
001|     mon         do_monthly_win_percentage           ~team monthly win percentage bar chart
001| 
001|     all         do_all                              ~all the charts
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| from logger import logger,info,debug,trace
011| from goodies import KWARG
012| import defs
013| ####################################################################################################
014| Log = logger('Season')
015| 
016| CMND = ''
017| ARGS = {
018|     #'team': 'twins',
019|     #'year':'2025',
020|     #'fpath': defs.BasePath,
021| }
022| 
023| 
024| ##------------------------------------------------------------------------------------------------##
025| Highlight = '#ff0000'
026| GrayedOut = '#9f9f9f'
027| 
028| TopTeam1 = '#ff0000'
029| TopTeam2 = '#009900'
030| TopTeam3 = '#0000ff'
031| BotTeam3 = '#666600'
032| BotTeam2 = '#009999'
033| BotTeam1 = '#7f007f'
034| 
035| DivisionColors = ['#ff0000', '#666600', '#00aa00', '#7f007f', '#0000ff']
036| 
037| 
038| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
039| class parameters (dict):
040|     '''Specialized dictionary for the chart maker.
040| 
040| New instances expect these required keyword arguments:
040|     title       ~title
040|     filename    ~filename (path and name)
040|     ylabel      ~Y-axis label
040|     ymax        ~y-axis maximum
040| 
040| Once created, of course, any parameter can be changed:
040| 
040|     params = parameters(<keyword-params>)
040|     params['margin.left'] = 0.075
040|     params['margin.bottom'] = 0.15
040| 
040| '''

041|     def __init__ (self, **kwargs):
042|         '''New instance. Create required parameters.'''
043| 
044|         self['suptitle'] = kwargs['title']
045|         self['filename'] = kwargs['filename']
046|         self['width']    = 10.0
047|         self['height']   =  6.0
048| 
049|         self['xlabel'] = 'Games'
050|         self['xmin']   =   0.5
051|         self['xmax']   = 162.5
052|         self['xtick0'] =  10
053|         self['xtick1'] =   2
054| 
055|         self['ylabel'] = kwargs['ylabel']
056|         self['ymin']   =  0
057|         self['ymax']   = kwargs['ymax']
058|         self['ytick0'] = 10
059|         self['ytick1'] =  2
060| 
061|         self['margin.left']   = 0.060
062|         self['margin.right']  = 0.990
063|         self['margin.bottom'] = 0.100
064|         self['margin.top']    = 0.940
065| 
066| 
067| ##================================================================================================##
068| def create_chart (plot_function, **params):
069|     '''Generate the multiple team progress chart.'''
070| 
071|     # Get the various required chart parameters...
072|     suptitle = params['suptitle']
073|     filename = params['filename']
074| 
075|     xlabel = params['xlabel']
076|     xmin   = params['xmin']
077|     xmax   = params['xmax']
078|     xtick0 = params['xtick0']
079|     xtick1 = params['xtick1']
080| 
081|     ylabel = params['ylabel']
082|     ymin   = params['ymin']
083|     ymax   = params['ymax']
084|     ytick0 = params['ytick0']
085|     ytick1 = params['ytick1']
086| 
087|     width    = params['width']
088|     height   = params['height']
089|     margin_l = params['margin.left']
090|     margin_r = params['margin.right']
091|     margin_b = params['margin.bottom']
092|     margin_t = params['margin.top']
093| 
094|     # Create a chart...
095|     fig, ax = plt.subplots()
096|     fig.set_figwidth(width)
097|     fig.set_figheight(height)
098|     fig.subplots_adjust(left=margin_l, right=margin_r, bottom=margin_b, top=margin_t)
099|     fig.suptitle(suptitle, fontsize=14, fontweight='bold')
100| 
101|     # Configure the X-axis...
102|     ax.set_xlabel(xlabel, fontsize=12, fontweight='bold')
103|     ax.set_xlim(xmin, xmax)
104|     ax.xaxis.set_major_locator(mltick.MultipleLocator(xtick0))
105|     ax.xaxis.set_minor_locator(mltick.MultipleLocator(xtick1))
106|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
107| 
108|     for tick in ax.xaxis.get_major_ticks():
109|         tick.label1.set_rotation('vertical')
110|         tick.label1.set_size(9)
111| 
112|     # Configure the Y-axis...
113|     ax.set_ylabel(ylabel, fontsize=12, fontweight='bold')
114|     ax.set_ylim(0, ymax)
115|     ax.yaxis.set_major_locator(mltick.MultipleLocator(ytick0))
116|     ax.yaxis.set_minor_locator(mltick.MultipleLocator(ytick1))
117|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
118| 
119|     # Configure the grid...
120|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
121|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
122|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
123|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
124| 
125|     # Plot the data...
126|     rv = plot_function(fig, ax)
127| 
128|     # Save the chart as a PNG file...
129|     fig.savefig(filename)
130|     defs.prn(f'wrote: {filename}')
131|     defs.prn()
132| 
133|     return filename
134| 
135| 
136| ##================================================================================================##
137| def do_mlb_wins_chart (**kwargs):
138|     '''CMND: Create a chart of wins in the MLB.'''
139|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
140|     fname = KWARG('fname', 'season-wins-MLB-{yr}.png', str, kwargs)
141|     tcode = KWARG('team', '', str, kwargs)
142|     yr = KWARG('yr', defs.DefaultYear, int, kwargs)
143|     Log.info(f'league-wins-chart:: {list(kwargs.keys())}')
144|     Log.debug(f'{fpath=}')
145|     Log.debug(f'{fname=}')
146|     Log.debug(f'{tcode=}')
147|     Log.debug(f'{yr=}')
148|     Log.info()
149| 
150|     if tcode:
151|         fname = fname.replace('.png', f'-{tcode}.png')
152|     file_name = path.join(fpath,fname) if fpath else fname
153|     file_name = file_name.format(**locals())
154|     Log.debug(f'{file_name=}')
155|     Log.debug()
156| 
157|     # Get team CSV data files...
158|     teams = [defs.CsvTeamGames(team_name) for team_name in defs.MlbTeams]
159| 
160|     # Extract teams win/loss data for plotting...
161|     ix_wl = teams[0].get_column_index('W/L')
162| 
163|     # For each team build a list of wins...
164|     for team in teams:
165|         team.team_name = defs.MlbTeams[team.team_code][2]
166|         team.plot_list = []
167|         team.wins = 0
168|         Log.trace(f'code={team.team_code}, name={team.team_name}')
169| 
170|         # For each game...
171|         for rcd in team:
172| 
173|             # Win or Lose?,...
174|             wl = rcd[ix_wl][0]
175|             if wl == 'W':
176|                 # Add another win...
177|                 team.wins += 1
178|             elif wl != 'L':
179|                 # Code wasn't a 'W' or an 'L'...
180|                 raise RuntimeError(f'Unknown W/L value: {wl}')
181| 
182|             # Add current wins to list...
183|             team.plot_list.append(team.wins)
184| 
185|     # Find maximums...
186|     xmax = 0
187|     ymax = 0
188|     for team in teams:
189|         if xmax < len(team.plot_list):
190|             xmax = len(team.plot_list)
191|         ym = defs.RoundUp(team.plot_list, 10)
192|         if ymax < ym:
193|             ymax = ym
194| 
195|     xs = list(range(1, xmax+1))
196| 
197|     # Ensure all plot lists have the same length...
198|     for team in teams:
199|         while len(team.plot_list) < xmax:
200|             team.plot_list.append(team.plot_list[-1])
201| 
202|     # Sort by wins...
203|     teams.sort(key=lambda team:team.wins, reverse=True)
204|     for ix,team in enumerate(teams, start=1):
205|         Log.trace(f'[{ix}] {team.team_name}: len={len(team.plot_list)} last={team.plot_list[-1]}')
206|     Log.trace()
207| 
208|     # Add colors to each team...
209|     for ix,team in enumerate(teams):
210|         if tcode == team.team_code:
211|             team.color = Highlight
212|             team.zorder = 51
213|         else:
214|             team.color = GrayedOut
215|             team.zorder = 11 + ix
216| 
217|     if not tcode:
218|         # Special colors for first and last three...
219|         teams[ 0].color = TopTeam1
220|         teams[ 1].color = TopTeam2
221|         teams[ 2].color = TopTeam3
222|         teams[-3].color = BotTeam3
223|         teams[-2].color = BotTeam2
224|         teams[-1].color = BotTeam1
225| 
226|         # Special colors for first and last three...
227|         teams[ 0].zorder = 56
228|         teams[ 1].zorder = 55
229|         teams[ 2].zorder = 54
230|         teams[-3].zorder = 53
231|         teams[-2].zorder = 52
232|         teams[-1].zorder = 51
233| 
234|     # Create the chart...
235|     params = parameters(
236|         title = 'MLB {yr} Team Season Wins'.format(**locals()),
237|         filename = file_name,
238|         ylabel = 'Wins',
239|         ymax = ymax,
240|     )
241|     def plot_function (fig, ax):
242|         # Plot traces...
243|         for team in teams:
244|             if 50 < team.zorder:
245|                 ax.plot(xs,team.plot_list, label=team.team_name, c=team.color, lw=2.0, alpha=0.7, zorder=team.zorder)
246|             else:
247|                 ax.plot(xs,team.plot_list, c=team.color, lw=2.0, alpha=0.7, zorder=team.zorder)
248| 
249|         # Legend...
250|         fig.legend(loc='upper left', ncols=1, fontsize=10, bbox_to_anchor=(0.060,0.940))
251| 
252|     return create_chart(plot_function, **params)
253| 
254| ##================================================================================================##
255| def do_league_wins_chart (**kwargs):
256|     '''CMND: Create a chart of wins in the league.'''
257|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
258|     fname = KWARG('fname', 'season-wins-{lg}-{yr}.png', str, kwargs)
259|     tcode = KWARG('team', '', str, kwargs)
260|     lg = KWARG('lg', 'AL', str, kwargs)
261|     yr = KWARG('yr', defs.DefaultYear, int, kwargs)
262|     Log.info(f'league-wins-chart:: {list(kwargs.keys())}')
263|     Log.debug(f'{fpath=}')
264|     Log.debug(f'{fname=}')
265|     Log.debug(f'{tcode=}')
266|     Log.debug(f'{lg=}')
267|     Log.debug(f'{yr=}')
268|     Log.info()
269| 
270|     if tcode:
271|         fname = fname.replace('.png', f'-{tcode}.png')
272|     file_name = path.join(fpath,fname) if fpath else fname
273|     file_name = file_name.format(**locals())
274|     Log.debug(f'{file_name=}')
275|     Log.debug()
276| 
277|     # Get a list of team names in the specified league...
278|     team_names = [nm for nm,rcd in defs.MlbTeams.items() if rcd[0]==lg]
279|     Log.trace(f'{team_names=}')
280|     Log.trace()
281| 
282|     # Get team CSV data files...
283|     teams = [defs.CsvTeamGames(name) for name in team_names]
284| 
285|     # Extract teams win/loss data for plotting...
286|     ix_wl = teams[0].get_column_index('W/L')
287| 
288|     # For each team build a list of wins...
289|     for team in teams:
290|         team.team_name = defs.MlbTeams[team.team_code][2]
291|         team.plot_list = []
292|         team.wins = 0
293|         Log.trace(f'code={team.team_code}, name={team.team_name}')
294| 
295|         # For each game...
296|         for rcd in team:
297| 
298|             # Win or Lose?,...
299|             wl = rcd[ix_wl][0]
300|             if wl == 'W':
301|                 # Add another win...
302|                 team.wins += 1
303|             elif wl != 'L':
304|                 # Code wasn't a 'W' or an 'L'...
305|                 raise RuntimeError(f'Unknown W/L value: {wl}')
306| 
307|             # Add current wins to list...
308|             team.plot_list.append(team.wins)
309| 
310|     # Find maximums...
311|     xmax = 0
312|     ymax = 0
313|     for team in teams:
314|         if xmax < len(team.plot_list):
315|             xmax = len(team.plot_list)
316|         ym = defs.RoundUp(team.plot_list, 10)
317|         if ymax < ym:
318|             ymax = ym
319| 
320|     xs = list(range(1, xmax+1))
321| 
322|     # Ensure all plot lists have the same length...
323|     for team in teams:
324|         while len(team.plot_list) < xmax:
325|             team.plot_list.append(team.plot_list[-1])
326| 
327|     # Sort by wins...
328|     teams.sort(key=lambda team:team.wins, reverse=True)
329|     for ix,team in enumerate(teams, start=1):
330|         Log.trace(f'[{ix}] {team.team_name}: len={len(team.plot_list)} last={team.plot_list[-1]}')
331|     Log.trace()
332| 
333|     # Add colors to each team...
334|     for ix,team in enumerate(teams):
335|         if tcode == team.team_code:
336|             team.color = Highlight
337|             team.zorder = 51
338|         else:
339|             team.color = GrayedOut
340|             team.zorder = 11 + ix
341| 
342|     if not tcode:
343|         # Special colors for first and last three...
344|         teams[ 0].color = TopTeam1
345|         teams[ 1].color = TopTeam2
346|         teams[ 2].color = TopTeam3
347|         teams[-3].color = BotTeam3
348|         teams[-2].color = BotTeam2
349|         teams[-1].color = BotTeam1
350| 
351|         # Special colors for first and last three...
352|         teams[ 0].zorder = 56
353|         teams[ 1].zorder = 55
354|         teams[ 2].zorder = 54
355|         teams[-3].zorder = 53
356|         teams[-2].zorder = 52
357|         teams[-1].zorder = 51
358| 
359|     # Create the chart...
360|     params = parameters(
361|         title = '{lg} {yr} Team Season Wins'.format(**locals()),
362|         filename = file_name,
363|         ylabel = 'Wins',
364|         ymax = ymax,
365|     )
366|     def plot_function (fig, ax):
367|         # Plot traces...
368|         for team in teams:
369|             if 50 < team.zorder:
370|                 ax.plot(xs,team.plot_list, label=team.team_name, c=team.color, lw=2.0, alpha=0.7, zorder=team.zorder)
371|             else:
372|                 ax.plot(xs,team.plot_list, c=team.color, lw=2.0, alpha=0.7, zorder=team.zorder)
373| 
374|         # Legend...
375|         fig.legend(loc='upper left', ncols=1, fontsize=10, bbox_to_anchor=(0.060,0.940))
376| 
377|     return create_chart(plot_function, **params)
378| 
379| ##================================================================================================##
380| def do_division_wins_chart (**kwargs):
381|     '''CMND: Create a chart of wins in the division.'''
382|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
383|     fname = KWARG('fname', 'season-wins-{lg}-{dv}-{yr}.png', str, kwargs)
384|     tcode = KWARG('team', '', str, kwargs)
385|     lg = KWARG('lg', 'AL', str, kwargs)
386|     dv = KWARG('dv', 'C' , str, kwargs)
387|     yr = KWARG('yr', defs.DefaultYear, int, kwargs)
388|     Log.info(f'division-wins-chart:: {list(kwargs.keys())}')
389|     Log.debug(f'{fpath=}')
390|     Log.debug(f'{fname=}')
391|     Log.debug(f'{tcode=}')
392|     Log.debug(f'{lg=}')
393|     Log.debug(f'{dv=}')
394|     Log.debug(f'{yr=}')
395|     Log.info()
396| 
397|     if tcode:
398|         fname = fname.replace('.png', f'-{tcode}.png')
399|     file_name = path.join(fpath,fname) if fpath else fname
400|     file_name = file_name.format(**locals())
401|     Log.debug(f'{file_name=}')
402|     Log.debug()
403| 
404|     # Get a list of team names in the specified league...
405|     fwhich = lambda rcd: ((rcd[0]==lg) and (rcd[1]==dv))
406|     team_names = [nm for nm,rcd in defs.MlbTeams.items() if fwhich(rcd)]
407|     Log.trace(f'{team_names=}')
408|     Log.trace()
409| 
410|     # Get team CSV data files...
411|     teams = [defs.CsvTeamGames(name) for name in team_names]
412| 
413|     # Extract teams win/loss data for plotting...
414|     ix_wl = teams[0].get_column_index('W/L')
415| 
416|     # For each team build a list of wins...
417|     for team in teams:
418|         team.team_name = defs.MlbTeams[team.team_code][2]
419|         team.plot_list = []
420|         team.wins = 0
421|         Log.trace(f'code={team.team_code}, name={team.team_name}')
422| 
423|         # For each game...
424|         for rcd in team:
425| 
426|             # Win or Lose?,...
427|             wl = rcd[ix_wl][0]
428|             if wl == 'W':
429|                 # Add another win...
430|                 team.wins += 1
431|             elif wl != 'L':
432|                 # Code wasn't a 'W' or an 'L'...
433|                 raise RuntimeError(f'Unknown W/L value: {wl}')
434| 
435|             # Add current wins to list...
436|             team.plot_list.append(team.wins)
437| 
438|     # Find maximums...
439|     xmax = 0
440|     ymax = 0
441|     for team in teams:
442|         if xmax < len(team.plot_list):
443|             xmax = len(team.plot_list)
444|         ym = defs.RoundUp(team.plot_list, 10)
445|         if ymax < ym:
446|             ymax = ym
447| 
448|     xs = list(range(1, xmax+1))
449| 
450|     # Ensure all plot lists have the same length...
451|     for team in teams:
452|         while len(team.plot_list) < xmax:
453|             team.plot_list.append(team.plot_list[-1])
454| 
455|     # Sort by wins...
456|     teams.sort(key=lambda team:team.wins, reverse=True)
457|     for ix,team in enumerate(teams, start=1):
458|         Log.trace(f'[{ix}] {team.team_name}: len={len(team.plot_list)} last={team.plot_list[-1]}')
459|     Log.trace()
460| 
461|     # Add colors to each team...
462|     if tcode:
463|         for ix,team in enumerate(teams):
464|             if team.team_code == tcode:
465|                 team.color = Highlight
466|                 team.zorder = 51
467|             else:
468|                 team.color = GrayedOut
469|                 team.zorder = 11 + ix
470|     else:
471|         for ix,team in enumerate(teams):
472|             team.color = DivisionColors[ix]
473|             team.zorder = 11 + ix
474| 
475|     # Create the chart...
476|     params = parameters(
477|         title = '{lg}-{dv} {yr} Team Season Wins'.format(**locals()),
478|         filename = file_name,
479|         ylabel = 'Wins',
480|         ymax = ymax,
481|     )
482|     def plot_function (fig, ax):
483|         '''Does the actual data plotting.'''
484|         for team in teams:
485|             if tcode:
486|                 if 50 < team.zorder:
487|                     ax.plot(xs,team.plot_list, label=team.team_name, c=team.color, lw=2.0, alpha=0.7, zorder=team.zorder)
488|                 else:
489|                     ax.plot(xs,team.plot_list, c=team.color, lw=2.0, alpha=0.7, zorder=team.zorder)
490|             else:
491|                 ax.plot(xs,team.plot_list, label=team.team_name, c=team.color, lw=2.0, alpha=0.7, zorder=team.zorder)
492| 
493|         # Legend...
494|         fig.legend(loc='upper left', ncols=1, fontsize=10, bbox_to_anchor=(0.060,0.940))
495| 
496|     return create_chart(plot_function, **params)
497| 
498| 
499| ##================================================================================================##
500| def do_season_500_chart (**kwargs):
501|     '''CMND: Create an Above/Below .500 Chart.'''
502|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
503|     fname = KWARG('fname', '{tcode}-{year}-500.png', str, kwargs)
504|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
505|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
506|     team_name = defs.MlbTeams[tcode][2]
507|     file_name = path.join(fpath,fname) if fpath else fname
508|     file_name = file_name.format(**locals())
509|     Log.info(f'season-500-chart:: {list(kwargs.keys())}')
510|     Log.debug(f'{fpath=}')
511|     Log.debug(f'{fname=}')
512|     Log.debug(f'{tcode=}')
513|     Log.debug(f'{year=}')
514|     Log.debug(f'{team_name=}')
515|     Log.debug(f'{file_name=}')
516|     Log.info()
517| 
518|     # Extract data from team's season...
519|     csv_data = defs.CsvTeamGames(tcode)
520|     dts = csv_data.get_column_data_date('Date')
521|     wls = csv_data.get_column_data('W/L')
522| 
523|     # Process data for chart...
524|     xs = []
525|     ys = []
526|     win = 0
527|     lose = 0
528| 
529|     for dt,wl in zip(dts, wls):
530|         match wl[0]:
531|             case 'W':
532|                 win += 1
533|             case 'L':
534|                 lose += 1
535|             case _:
536|                 raise RuntimeError(f'Unknown W/L value: {wl}')
537| 
538|         xs.append(dt)
539|         ys.append(win / (win+lose))
540| 
541|     xmin = xs[0] - dttm.timedelta(1)
542|     xmax = xs[-1] + dttm.timedelta(1)
543| 
544|     # Create a chart...
545|     fig, ax = plt.subplots()
546|     fig.set_figwidth(10.0)
547|     fig.set_figheight(4.0)
548|     fig.subplots_adjust(left=0.080, right=0.990, bottom=0.13, top=0.92)
549| 
550|     fig.suptitle(f'{team_name} {year} Win/Loss Record', fontsize=14, fontweight='bold')
551| 
552|     # Configure X-axis...
553|     ax.set_xlabel('Date', fontsize=12, fontweight='bold')
554|     ax.xaxis_date()
555|     ax.set_xlim(xmin, xmax)
556|     ax.xaxis.set_major_locator(mldate.MonthLocator())
557|     ax.xaxis.set_minor_locator(mldate.DayLocator(bymonthday=[8,15,22]))
558|     ax.xaxis.set_major_formatter(mldate.DateFormatter('%b'))
559| 
560|     # Configure Y-axis...
561|     ax.set_ylabel('Win %', fontsize=12, fontweight='bold')
562|     ax.set_ylim(0.2, 0.7)
563|     ax.yaxis.set_major_locator(mltick.MultipleLocator(0.1))
564|     ax.yaxis.set_minor_locator(mltick.NullLocator())
565|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%.3f'))
566| 
567|     # Configure grid...
568|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
569|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
570|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
571|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
572| 
573|     # Plot data...
574|     ax.axhline(0.5, lw=3.0, color='#000000', alpha=0.75, zorder=10)
575|     ax.plot(xs,ys, color='#0000ff', lw=2.0, alpha=0.95, zorder=11)
576| 
577|     # Save the chart...
578|     fig.savefig(file_name)
579|     defs.prn(f'wrote: {file_name}')
580|     defs.prn()
581|     return file_name
582| 
583| 
584| ##================================================================================================##
585| def do_monthly_win_percentage (**kwargs):
586|     '''CMND: Create a monthly win percentage chart.'''
587|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
588|     fname = KWARG('fname', '{tcode}-{year}-mon-win-pct.png', str, kwargs)
589|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
590|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
591|     team_name = defs.MlbTeams[tcode][2]
592|     file_name = path.join(fpath,fname) if fpath else fname
593|     file_name = file_name.format(**locals())
594|     Log.info(f'monthly-win-percentage:: {list(kwargs.keys())}')
595|     Log.debug(f'{fpath=}')
596|     Log.debug(f'{fname=}')
597|     Log.debug(f'{tcode=}')
598|     Log.debug(f'{year=}')
599|     Log.debug(f'{team_name=}')
600|     Log.debug(f'{file_name=}')
601|     Log.info()
602| 
603|     # Extract data from team's season...
604|     csv_data = defs.CsvTeamGames(tcode)
605|     dts = csv_data.get_column_data_date('Date')
606|     wls = csv_data.get_column_data('W/L')
607| 
608|     months = {n:[0,0] for n in [3,4,5,6,7,8,9]}
609| 
610|     for dt,wl in zip(dts, wls):
611|         match wl[0]:
612|             case 'W':
613|                 months[dt.month][1] += 1
614|             case 'L':
615|                 pass
616|             case _:
617|                 raise RuntimeError(f'Unknown W/L value: {wl}')
618| 
619|         # Bump total games in the month...
620|         months[dt.month][0] += 1
621| 
622|     # Log stats data...
623|     for m in months:
624|         t = months[m]
625|         Log.trace(f'{m}: won {t[1]} of {t[0]} games ({t[1]/t[0]:.3f}).')
626|     Log.trace()
627| 
628|     xs = [dttm.date(defs.DefaultYear,m,1) for m in months.keys()]
629|     ys = [months[m][1]/months[m][0] for m in months.keys()]
630|     Log.debug(xs)
631|     Log.debug(ys)
632|     Log.debug()
633|     xmin = dttm.date(defs.DefaultYear, 2, 15)
634|     xmax = dttm.date(defs.DefaultYear, 9, 15)
635| 
636|     # Create a chart...
637|     fig, ax = plt.subplots()
638|     fig.set_figwidth(10.0)
639|     fig.set_figheight(4.0)
640|     fig.subplots_adjust(left=0.080, right=0.990, bottom=0.13, top=0.92)
641| 
642|     fig.suptitle(f'{team_name} {year} - Monthly Win Percentage', fontsize=15, fontweight='bold')
643| 
644|     # Configure X-axis...
645|     ax.set_xlabel('Month', fontsize=12, fontweight='bold')
646|     ax.xaxis_date()
647|     ax.set_xlim(xmin, xmax)
648|     ax.xaxis.set_major_locator(mldate.MonthLocator())
649|     ax.xaxis.set_minor_locator(mltick.NullLocator())
650|     ax.xaxis.set_major_formatter(mldate.DateFormatter('%b'))
651| 
652|     for tick in ax.xaxis.get_major_ticks():
653|         tick.label1.set_size(11)
654|         tick.label1.set_fontweight('bold')
655| 
656|     # Configure Y-axis...
657|     ax.set_ylabel('Win Percentage', fontsize=12, fontweight='bold')
658|     ax.set_ylim(0.000, 1.000)
659|     ax.yaxis.set_major_locator(mltick.MultipleLocator(0.1))
660|     ax.yaxis.set_minor_locator(mltick.NullLocator())
661|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%.3f'))
662| 
663|     # Configure grid...
664|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
665|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
666|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
667|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
668| 
669|     # Plot data...
670|     ax.bar(xs,ys, width=20, edgecolor='#000000', lw=1.7, alpha=1.0, zorder=11)
671| 
672|     bboxprops = dict(boxstyle='Round,pad=0.4', facecolor='white', edgecolor='#000000', lw=2)
673|     textprops = dict(color='#000000', bbox=bboxprops, ha='center', size=16, weight='bold')
674|     for x,y in zip(xs,ys):
675|         ax.text(x,y+0.075, f'{y:.3f}', **textprops)
676| 
677|     # Save the chart...
678|     fig.savefig(file_name)
679|     defs.prn(f'wrote: {file_name}')
680|     defs.prn()
681|     return file_name
682| 
683| 
684| ##================================================================================================##
685| def do_all (**kwargs):
686|     '''Do all charts.'''
687|     Log.info(f'do-all:: {list(kwargs.keys())}')
688|     Log.info()
689| 
690|     rvs = []
691| 
692|     # For each league...
693|     for lg in ['AL', 'NL']:
694|         kwargs['lg'] = lg
695| 
696|         # For each league division...
697|         for dv in ['W', 'C', 'E']:
698|             kwargs['dv'] = dv
699| 
700|             # Create a Division Wins chart...
701|             rvs.append(do_division_wins_chart(**kwargs))
702| 
703|     # For each league...
704|     for lg in ['AL', 'NL']:
705|         kwargs['lg'] = lg
706| 
707|         # Create a League Wins chart...
708|         rvs.append(do_league_wins_chart(**kwargs))
709| 
710|     # For the whole MLB...
711|     rvs.append(do_mlb_wins_chart(**kwargs))
712| 
713|     # Also do the monthly win percentage chart...
714|     rvs.append(do_monthly_win_percentage(**kwargs))
715| 
716|     return rvs
717| 
718| ##================================================================================================##
719| def do_test (**kwargs):
720|     '''CMND: Do a test.'''
721|     fpath = KWARG('fpath', defs.BasePath, str, kwargs)
722|     fname = KWARG('fname', 'test-{tcode}-{year}.png', str, kwargs)
723|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
724|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
725|     team_name = defs.MlbTeams[tcode][2]
726|     file_name = path.join(fpath,fname) if fpath else fname
727|     file_name = file_name.format(**locals())
728|     Log.info(f'test:: {list(kwargs.keys())}')
729|     Log.debug(f'{fpath=}')
730|     Log.debug(f'{fname=}')
731|     Log.debug(f'{tcode=}')
732|     Log.debug(f'{year=}')
733|     Log.debug(f'{team_name=}')
734|     Log.debug(f'{file_name=}')
735|     Log.info()
736| 
737|     # extract data from team's season...
738|     csv_data = defs.CsvTeamGames(tcode)
739| 
740|     Log.info()
741|     return file_name
742| 
743| ####################################################################################################
744| def dispatch (cmd, **kwargs):
745|     '''Dispatch to a module function based on CMD.'''
746|     Log.info(f'CMD: {cmd}')
747|     for kw in kwargs:
748|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
749|     Log.info()
750| 
751|     if cmd == 'div':  return do_division_wins_chart     (**kwargs)
752|     if cmd == 'lea':  return do_league_wins_chart       (**kwargs)
753|     if cmd == 'mlb':  return do_mlb_wins_chart          (**kwargs)
754|     if cmd == '500':  return do_season_500_chart        (**kwargs)
755|     if cmd == 'mon':  return do_monthly_win_percentage  (**kwargs)
756|     if cmd == 'all':  return do_all                     (**kwargs)
757|     if cmd == 'test': return do_test                    (**kwargs)
758| 
759|     return 'Nothing to do!'
760| ####################################################################################################
761| if __name__ == '__main__':
762|     print(f'autorun: {argv[0]}')
763|     Log.start(path.join(defs.BasePath,'season.log'))
764|     Log.level(trace())
765|     Log.info(argv[0])
766|     cmd = argv[1] if 1 < len(argv) else CMND
767|     kwargs = ARGS
768|     for a in argv[2:]:
769|         nv = a.split('=', 1)
770|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
771|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
772|     Log.info()
773|     try:
774|         print(f'CMD: {cmd}')
775|         print()
776|         obj = dispatch(cmd, **kwargs)
777|         print(obj)
778|         print()
779|         Log.info(obj)
780|         Log.info()
781|     except:
782|         etype, evalue, tb = exc_info()
783|         ts = extract_tb(tb)
784|         Log.error()
785|         Log.error(f'{etype.__name__}: {evalue!s}')
786|         Log.error()
787|         for t in ts[-5:]:
788|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
789|             Log.error(f' {t[3]}')
790|             Log.error()
791|         raise
792|     finally:
793|         Log.end()
794| ####################################################################################################
795| '''eof'''
796|