games.html


001| """Baseball Charts - Season Webpages (Stats & Games).
001| 
001| Commands:
001|     stats       do_season_stats_webpage             ~create stats webpage
001|     games       do_season_games_webpage             ~create games webpage
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| from logger import logger,info,debug,trace
007| from goodies import KWARG, marker
008| from facts import MonthNames
009| from webpage import WebPage
010| import defs
011| ####################################################################################################
012| Log = logger('Games')
013| 
014| CMND = 'stats'
015| ARGS = {
016|     #'team':'twins',
017|     #'year':'2025',
018|     #'fpath': defs.BasePath,
019| }
020| 
021| ##------------------------------------------------------------------------------------------------##
022| SeasonStatsCSS = """\
022| body #PageBody table {
022|     background-color: #7f7f7f;
022|     font-family: sans-serif;
022|     font-size: 11pt;
022|     border-spacing: 0 2px;
022|     padding: 0 2px 0 2px;
022|     border: 3px solid black;
022|     margin: 0 12pt 6pt 16pt;
022| }
022| body #PageBody table thead th,
022| body #PageBody table tfoot th {
022|     background-color: black;
022|     color: white;
022|     font-size: 10pt;
022|     font-weight: bold;
022|     text-align: center;
022|     white-space: nowrap;
022|     padding: 5px;
022|     border: 0;
022| }
022| body #PageBody table tbody th {
022|     background-color: navy;
022|     color: white;
022|     white-space: nowrap;
022|     font-weight: bold;
022|     text-align: left;
022|     padding: 2px 19px 3px 11px;
022|     border: 0;
022| }
022| body #PageBody table tbody td {
022|     background-color: white;
022|     color: black;
022|     white-space: nowrap;
022|     font-weight: normal;
022|     text-align: right;
022|     padding: 2px 6px 3px 6px;
022|     border: 0;
022| }
022| body #PageBody table .Win  {background-color: #7fff7f;}
022| body #PageBody table .Lose {background-color: #ff7777;}
022| body #PageBody table .LineLeft {border-left: 1px solid black;}
022| body #PageBody table .LineRight {border-right: 1px solid black;}
022| """

023| 
024| ##------------------------------------------------------------------------------------------------##
025| SeasonGamesCSS = """\
025| body #PageBody table {
025|     font-family: sans-serif;
025|     font-size: 9pt;
025|     border-spacing: 0 2px;
025|     padding: 3px 0 5px 0;
025|     border: 3px solid black;
025|     margin: 0 12pt 6pt 9pt;
025| }
025| body #PageBody table thead th,
025| body #PageBody table tfoot th {
025|     background-color: black;
025|     color: white;
025|     font-size: 10pt;
025|     font-weight: bold;
025|     text-align: center;
025|     white-space: nowrap;
025|     padding: 5px;
025|     border: 0;
025| }
025| body #PageBody table tbody th {
025|     background-color: navy;
025|     color: white;
025|     font-weight: normal;
025|     text-align: right;
025|     white-space: nowrap;
025|     padding: 1px 4px 2px 8px;
025|     border: 0;
025| }
025| body #PageBody table tbody td {
025|     background-color: white;
025|     color: black;
025|     font-weight: normal;
025|     white-space: nowrap;
025|     padding: 1px 6px 2px 6px;
025|     border: 0;
025| }
025| body #PageBody table tbody td.date {
025|     color: blue;
025|     text-align: left;
025|     padding-right: 17px;
025| }
025| body #PageBody table tbody td.type {
025|     text-align: right;
025|     padding-right: 1px;
025| }
025| body #PageBody table tbody td.name {
025|     font-weight: bold;
025|     text-align: left;
025|     padding-left: 1px;
025|     padding-right: 17px;
025| }
025| body #PageBody table tbody td.runs {
025|     font-family: monospace;
025|     font-weight: bold;
025|     text-align: right;
025|     padding-left: 5px;
025|     padding-right: 5px;
025| }
025| body #PageBody table tbody td.hits {
025|     font-family: monospace;
025|     text-align: right;
025|     padding-left: 3px;
025|     padding-right: 3px;
025| }
025| body #PageBody table tbody td.score {
025|     font-weight: bold;
025|     text-align: center;
025|     padding-left: 8px;
025|     padding-right: 8px;
025| }
025| body #PageBody table .Win  {background-color: #7fff7f;}
025| body #PageBody table .Lose {background-color: #ff7777;}
025| body #PageBody table .Tie  {background-color: #ffff00;}
025| body #PageBody table .LineLeft {border-left: 1px solid black;}
025| body #PageBody table .LineRight {border-right: 1px solid black;}
025| body #PageBody table .LineTop {border-top: 1px solid black;}
025| body #PageBody table .LineBot {border-bottom: 1px solid black;}
025| """

026| 
027| ##================================================================================================##
028| def do_season_stats_webpage (**kwargs):
029|     '''CMND: Create a webpage listing team's season stats.'''
030|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
031|     fname = KWARG('fname', '{tcode}-{year}-stats.html', str, kwargs)
032|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
033|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
034|     team_name = defs.MlbTeams[tcode][2]
035|     team_city = defs.MlbTeams[tcode][3]
036|     file_name = path.join(fpath,fname) if fpath else fname
037|     file_name = file_name.format(**locals())
038|     Log.info(f'season-stats-webpage:: {list(kwargs.keys())}')
039|     Log.debug(f'{fpath=}')
040|     Log.debug(f'{fname=}')
041|     Log.debug(f'{tcode=}')
042|     Log.debug(f'{year=}')
043|     Log.debug(f'{team_name=}')
044|     Log.debug(f'{file_name=}')
045|     Log.info()
046|     win_pct = lambda w,l: float(w)/(float(w)+float(l))
047| 
048|     # Extract data from team's season...
049|     season_data = defs.CsvTeamGames(tcode)
050|     batting_data = defs.CsvTeamGamesBatting(tcode)
051|     pitching_data = defs.CsvTeamGamesPitching(tcode)
052| 
053|     game_data = [marker(start=1, dtype=int)]                    # 0
054|     game_data.append( season_data.get_column_data_date('Date') )     # 1
055|     game_data.append( season_data.get_column_data('Opp') )      # 2
056|     game_data.append( season_data.get_column_data(4) )          # 3
057|     game_data.append( batting_data.get_column_data('Rslt') )    # 4
058|     game_data.append( season_data.get_column_data('W-L') )      # 5
059|     game_data.append( season_data.get_column_data_int('R') )    # 6
060|     game_data.append( season_data.get_column_data_int('RA') )   # 7
061|     game_data.append( batting_data.get_column_data_int('H') )   # 8
062|     game_data.append( pitching_data.get_column_data_int('H') )  # 9
063|     game_data.append( batting_data.get_column_data_int('2B') )  # 10
064|     game_data.append( pitching_data.get_column_data_int('2B') ) # 11
065|     game_data.append( batting_data.get_column_data_int('3B') )  # 12
066|     game_data.append( pitching_data.get_column_data_int('3B') ) # 13
067|     game_data.append( batting_data.get_column_data_int('HR') )  # 14
068|     game_data.append( pitching_data.get_column_data_int('HR') ) # 15
069|     game_data.append( batting_data.get_column_data_int('SO') )  # 16
070|     game_data.append( pitching_data.get_column_data_int('SO') ) # 17
071|     game_data.append( batting_data.get_column_data_int('BB') )  # 18
072|     game_data.append( pitching_data.get_column_data_int('BB') ) # 19
073| 
074|     stats = {
075|         'R':0 , 'r':0 , 'H':0 , 'h':0 ,
076|         '2B':0, '2b':0, '3B':0, '3b':0,
077|         'HR':0, 'hr':0, 'SO':0, 'so':0, 'BB':0, 'bb':0,
078|     }
079|     total = [0, 0, 0] # total-games; won-games; lost-games
080|     home = [0, 0, 0]
081|     away = [0, 0, 0]
082|     months = {3:[0,0,0], 4:[0,0,0], 5:[0,0,0], 6:[0,0,0], 7:[0,0,0], 8:[0,0,0], 9:[0,0,0], 10:[0,0,0]}
083|     first_half = [0, 0, 0]
084|     second_half = [0, 0, 0]
085|     runs_0 = [0, 0, 0]
086|     runs_1 = [0, 0, 0]
087|     runs_4 = [0, 0, 0]
088|     runs_9 = [0, 0, 0]
089|     runs_x = [0, 0, 0]
090|     rdif_1 = [0, 0, 0]
091|     rdif_2 = [0, 0, 0]
092|     rdif_5 = [0, 0, 0]
093|     rdif_x = [0, 0, 0]
094| 
095|     for ix,dt,opp,loc,res,wl,rs,ra,hs,ha,b2s,b2a,b3s,b3a,hrs,hra,sos,soa,bbs,bba in zip(*game_data):
096|         Log.trace(f'{ix:3d}: {dt} {loc}{opp} {rs} R {hs} H {b2s} 2B {b3s} 3B {hrs} HR {sos} SO {bbs} BB')
097|         if res not in ['W', 'L']:
098|             raise RuntimeError(f'Unexpected game result: {res}')
099| 
100|         # Add game stats to totals...
101|         stats['R']  += rs;  stats['r']  += ra
102|         stats['H']  += hs;  stats['h']  += ha
103|         stats['2B'] += b2s; stats['2b'] += b2a
104|         stats['3B'] += b3s; stats['3b'] += b3a
105|         stats['HR'] += hrs; stats['hr'] += hra
106|         stats['SO'] += sos; stats['so'] += soa
107|         stats['BB'] += bbs; stats['bb'] += bba
108| 
109|         # Total...
110|         total[0] += 1
111|         if res == 'W':
112|             total[1] += 1
113|         else:
114|             total[2] += 1
115| 
116|         # Months splits...
117|         months[dt.month][0] += 1
118|         if res == 'W':
119|             months[dt.month][1] += 1
120|         else:
121|             months[dt.month][2] += 1
122| 
123|         # Home/Away...
124|         if loc == '@':
125|             away[0] += 1
126|             if res == 'W':
127|                 away[1] += 1
128|             else:
129|                 away[2] += 1
130|         else:
131|             home[0] += 1
132|             if res == 'W':
133|                 home[1] += 1
134|             else:
135|                 home[2] += 1
136| 
137|         # Season halves split...
138|         if ix <= 81:
139|             first_half[0] += 1
140|             if res == 'W':
141|                 first_half[1] += 1
142|             else:
143|                 first_half[2] += 1
144|         else:
145|             second_half[0] += 1
146|             if res == 'W':
147|                 second_half[1] += 1
148|             else:
149|                 second_half[2] += 1
150| 
151|         # Number of runs scored splits...
152|         if rs == 0:
153|             runs_0[0] += 1
154|             if res == 'W':
155|                 runs_0[1] += 1
156|             else:
157|                 runs_0[2] += 1
158|         elif rs == 1:
159|             runs_1[0] += 1
160|             if res == 'W':
161|                 runs_1[1] += 1
162|             else:
163|                 runs_1[2] += 1
164|         elif 1 < rs <= 4:
165|             runs_4[0] += 1
166|             if res == 'W':
167|                 runs_4[1] += 1
168|             else:
169|                 runs_4[2] += 1
170|         elif 4 < rs <= 9:
171|             runs_9[0] += 1
172|             if res == 'W':
173|                 runs_9[1] += 1
174|             else:
175|                 runs_9[2] += 1
176|         else:
177|             runs_x[0] += 1
178|             if res == 'W':
179|                 runs_x[1] += 1
180|             else:
181|                 runs_x[2] += 1
182| 
183|         # Run differential splits...
184|         dif = abs(rs - ra)
185|         if dif == 1:
186|             rdif_1[0] += 1
187|             if res == 'W':
188|                 rdif_1[1] += 1
189|             else:
190|                 rdif_1[2] += 1
191|         elif dif == 2:
192|             rdif_2[0] += 1
193|             if res == 'W':
194|                 rdif_2[1] += 1
195|             else:
196|                 rdif_2[2] += 1
197|         elif 3 <= dif <= 5:
198|             rdif_5[0] += 1
199|             if res == 'W':
200|                 rdif_5[1] += 1
201|             else:
202|                 rdif_5[2] += 1
203|         else:
204|             rdif_x[0] += 1
205|             if res == 'W':
206|                 rdif_x[1] += 1
207|             else:
208|                 rdif_x[2] += 1
209| 
210|     Log.trace()
211| 
212|     props = dict(
213|         h1 = f'Baseball {year}',
214|         h2 = f'{team_city} {team_name}',
215|         h3 = f'{team_name} Stats {year}',
216|         css = ['/basic.css'],
217|         csstxt = SeasonStatsCSS
218|     )
219|     pg = WebPage(f'{team_city} {team_name} Stats {year}', **props)
220| 
221|     pg.add('<table>')
222| 
223|     pg.add('<thead>')
224|     pg.add('<th>Stat</th>')
225|     pg.add('<th>Games</th>')
226|     pg.add(f'<th>{team_name}</th>')
227|     pg.add('<th>Opps</th>')
228|     pg.add('<th>&Delta;</th>')
229|     pg.add('<th>%</th>')
230|     pg.add('</thead>')
231| 
232|     pg.add('<tfoot>')
233|     pg.add('<th>Stat</th>')
234|     pg.add('<th>Games</th>')
235|     pg.add(f'<th>{team_name}</th>')
236|     pg.add('<th>Opps</th>')
237|     pg.add('<th>&Delta;</th>')
238|     pg.add('<th>%</th>')
239|     pg.add('</tfoot>')
240| 
241|     pg.add('<tbody>')
242| 
243|     clr = 'Win' if total[2] < total[1] else 'Lose'
244|     pg.add('<tr>')
245|     pg.add('<th>Total</th>')
246|     pg.add(f'<td class="LineRight">{total[0]}</td>')
247|     pg.add(f'<td>{total[1]}</td>')
248|     pg.add(f'<td>{total[2]}</td>')
249|     pg.add(f'<td class="{clr} LineLeft">{total[1]-total[2]}</td>')
250|     pg.add(f'<td class="{clr} LineLeft">{total[1]/total[0]:.3f}</td>')
251|     pg.add('</tr>')
252| 
253|     pg.add('<tr><td colspan="5" style="height:4px; background-color:transparent;"></td></tr>')
254| 
255|     clr = 'Win' if home[2] < home[1] else 'Lose'
256|     pg.add('<tr>')
257|     pg.add('<th>Home</th>')
258|     pg.add(f'<td class="LineRight">{home[0]}</td>')
259|     pg.add(f'<td>{home[1]}</td>')
260|     pg.add(f'<td>{home[2]}</td>')
261|     pg.add(f'<td class="{clr} LineLeft">{home[1]-home[2]}</td>')
262|     pg.add(f'<td class="{clr} LineLeft">{home[1]/home[0]:.3f}</td>')
263|     pg.add('</tr>')
264| 
265|     clr = 'Win' if away[2] < away[1] else 'Lose'
266|     pg.add('<tr>')
267|     pg.add('<th>Away</th>')
268|     pg.add(f'<td class="LineRight">{away[0]}</td>')
269|     pg.add(f'<td>{away[1]}</td>')
270|     pg.add(f'<td>{away[2]}</td>')
271|     pg.add(f'<td class="{clr} LineLeft">{away[1]-away[2]}</td>')
272|     pg.add(f'<td class="{clr} LineLeft">{away[1]/away[0]:.3f}</td>')
273|     pg.add('</tr>')
274| 
275|     pg.add('<tr><td colspan="5" style="height:4px; background-color:transparent;"></td></tr>')
276| 
277|     clr = 'Win' if first_half[2] < first_half[1] else 'Lose'
278|     pg.add('<tr>')
279|     pg.add('<th>First Half</th>')
280|     pg.add(f'<td class="LineRight">{first_half[0]}</td>')
281|     pg.add(f'<td>{first_half[1]}</td>')
282|     pg.add(f'<td>{first_half[2]}</td>')
283|     pg.add(f'<td class="{clr} LineLeft">{first_half[1]-first_half[2]}</td>')
284|     pg.add(f'<td class="{clr} LineLeft">{first_half[1]/first_half[0]:.3f}</td>')
285|     pg.add('</tr>')
286| 
287|     clr = 'Win' if second_half[2] < second_half[1] else 'Lose'
288|     pg.add('<tr>')
289|     pg.add('<th>Second Half</th>')
290|     pg.add(f'<td class="LineRight">{second_half[0]}</td>')
291|     pg.add(f'<td>{second_half[1]}</td>')
292|     pg.add(f'<td>{second_half[2]}</td>')
293|     pg.add(f'<td class="{clr} LineLeft">{second_half[1]-second_half[2]}</td>')
294|     pg.add(f'<td class="{clr} LineLeft">{second_half[1]/second_half[0]:.3f}</td>')
295|     pg.add('</tr>')
296| 
297|     pg.add('<tr><td colspan="5" style="height:4px; background-color:transparent;"></td></tr>')
298| 
299|     for month in sorted(months):
300|         tot,wins,losses = months[month]
301|         if tot == 0:
302|             continue
303|         clr = 'Win' if losses < wins else 'Lose'
304|         pg.add('<tr>')
305|         pg.add(f'<th>{MonthNames[month]}</th>')
306|         pg.add(f'<td class="LineRight">{tot}</td>')
307|         pg.add(f'<td>{wins}</td>')
308|         pg.add(f'<td>{losses}</td>')
309|         pg.add(f'<td class="{clr} LineLeft">{wins-losses}</td>')
310|         pg.add(f'<td class="{clr} LineLeft">{win_pct(wins,losses):.3f}</td>')
311|         pg.add('</tr>')
312| 
313|     pg.add('<tr><td colspan="5" style="height:10px; background-color:transparent;"></td></tr>')
314| 
315|     clr = 'Win' if stats["r"] < stats["R"] else 'Lose'
316|     pg.add('<tr>')
317|     pg.add('<th>Runs</th>')
318|     pg.add(f'<td class="LineRight"></td>')
319|     pg.add(f'<td>{stats["R"]}</td>')
320|     pg.add(f'<td>{stats["r"]}</td>')
321|     pg.add(f'<td class="{clr} LineLeft">{stats["R"]-stats["r"]:+d}</td>')
322|     pg.add(f'<td class="{clr} LineLeft">{win_pct(stats["R"],stats["r"]):.3f}</td>')
323|     pg.add('</tr>')
324| 
325|     clr = 'Win' if stats["h"] < stats["H"] else 'Lose'
326|     pg.add('<tr>')
327|     pg.add('<th>Hits</th>')
328|     pg.add(f'<td class="LineRight"></td>')
329|     pg.add(f'<td>{stats["H"]}</td>')
330|     pg.add(f'<td>{stats["h"]}</td>')
331|     pg.add(f'<td class="{clr} LineLeft">{stats["H"]-stats["h"]:+d}</td>')
332|     pg.add(f'<td class="{clr} LineLeft">{win_pct(stats["H"],stats["h"]):.3f}</td>')
333|     pg.add('</tr>')
334| 
335|     clr = 'Win' if stats["2b"] < stats["2B"] else 'Lose'
336|     pg.add('<tr>')
337|     pg.add('<th>Doubles</th>')
338|     pg.add(f'<td class="LineRight"></td>')
339|     pg.add(f'<td>{stats["2B"]}</td>')
340|     pg.add(f'<td>{stats["2b"]}</td>')
341|     pg.add(f'<td class="{clr} LineLeft">{stats["2B"]-stats["2b"]:+d}</td>')
342|     pg.add(f'<td class="{clr} LineLeft">{win_pct(stats["2B"],stats["2b"]):.3f}</td>')
343|     pg.add('</tr>')
344| 
345|     clr = 'Win' if stats["3b"] < stats["3B"] else 'Lose'
346|     pg.add('<tr>')
347|     pg.add('<th>Triples</th>')
348|     pg.add(f'<td class="LineRight"></td>')
349|     pg.add(f'<td>{stats["3B"]}</td>')
350|     pg.add(f'<td>{stats["3b"]}</td>')
351|     pg.add(f'<td class="{clr} LineLeft">{stats["3B"]-stats["3b"]:+d}</td>')
352|     pg.add(f'<td class="{clr} LineLeft">{win_pct(stats["3B"],stats["3b"]):.3f}</td>')
353|     pg.add('</tr>')
354| 
355|     clr = 'Win' if stats["hr"] < stats["HR"] else 'Lose'
356|     pg.add('<tr>')
357|     pg.add('<th>Home Runs</th>')
358|     pg.add(f'<td class="LineRight"></td>')
359|     pg.add(f'<td>{stats["HR"]}</td>')
360|     pg.add(f'<td>{stats["hr"]}</td>')
361|     pg.add(f'<td class="{clr} LineLeft">{stats["HR"]-stats["hr"]:+d}</td>')
362|     pg.add(f'<td class="{clr} LineLeft">{win_pct(stats["HR"],stats["hr"]):.3f}</td>')
363|     pg.add('</tr>')
364| 
365|     clr = 'Win' if stats["SO"] < stats["so"] else 'Lose'
366|     pg.add('<tr>')
367|     pg.add('<th>Strikeouts</th>')
368|     pg.add(f'<td class="LineRight"></td>')
369|     pg.add(f'<td>{stats["SO"]}</td>')
370|     pg.add(f'<td>{stats["so"]}</td>')
371|     pg.add(f'<td class="{clr} LineLeft">{stats["SO"]-stats["so"]:+d}</td>')
372|     pg.add(f'<td class="{clr} LineLeft">{win_pct(stats["SO"],stats["so"]):.3f}</td>')
373|     pg.add('</tr>')
374| 
375|     clr = 'Win' if stats["bb"] < stats["BB"] else 'Lose'
376|     pg.add('<tr>')
377|     pg.add('<th>Walks</th>')
378|     pg.add(f'<td class="LineRight"></td>')
379|     pg.add(f'<td>{stats["BB"]}</td>')
380|     pg.add(f'<td>{stats["bb"]}</td>')
381|     pg.add(f'<td class="{clr} LineLeft">{stats["BB"]-stats["bb"]:+d}</td>')
382|     pg.add(f'<td class="{clr} LineLeft">{win_pct(stats["BB"],stats["bb"]):.3f}</td>')
383|     pg.add('</tr>')
384| 
385|     pg.add('<tr><td colspan="5" style="height:10px; background-color:transparent;"></td></tr>')
386| 
387|     clr = 'Win' if runs_0[2] < runs_0[1] else 'Lose'
388|     pg.add('<tr>')
389|     pg.add('<th>0 Runs Scored</th>')
390|     pg.add(f'<td class="LineRight">{runs_0[0]}</td>')
391|     pg.add(f'<td>{runs_0[1]}</td>')
392|     pg.add(f'<td>{runs_0[2]}</td>')
393|     pg.add(f'<td class="{clr} LineLeft">{runs_0[1]-runs_0[2]:+d}</td>')
394|     pg.add(f'<td class="{clr} LineLeft">{win_pct(runs_0[1],runs_0[2]):.3f}</td>')
395|     pg.add('</tr>')
396| 
397|     clr = 'Win' if runs_1[2] < runs_1[1] else 'Lose'
398|     pg.add('<tr>')
399|     pg.add('<th>1 Run Scored</th>')
400|     pg.add(f'<td class="LineRight">{runs_1[0]}</td>')
401|     pg.add(f'<td>{runs_1[1]}</td>')
402|     pg.add(f'<td>{runs_1[2]}</td>')
403|     pg.add(f'<td class="{clr} LineLeft">{runs_1[1]-runs_1[2]:+d}</td>')
404|     pg.add(f'<td class="{clr} LineLeft">{win_pct(runs_1[1],runs_1[2]):.3f}</td>')
405|     pg.add('</tr>')
406| 
407|     clr = 'Win' if runs_4[2] < runs_4[1] else 'Lose'
408|     pg.add('<tr>')
409|     pg.add('<th>2-4 Runs Scored</th>')
410|     pg.add(f'<td class="LineRight">{runs_4[0]}</td>')
411|     pg.add(f'<td>{runs_4[1]}</td>')
412|     pg.add(f'<td>{runs_4[2]}</td>')
413|     pg.add(f'<td class="{clr} LineLeft">{runs_4[1]-runs_4[2]:+d}</td>')
414|     pg.add(f'<td class="{clr} LineLeft">{win_pct(runs_4[1],runs_4[2]):.3f}</td>')
415|     pg.add('</tr>')
416| 
417|     clr = 'Win' if runs_9[2] < runs_9[1] else 'Lose'
418|     pg.add('<tr>')
419|     pg.add('<th>5-9 Runs Scored</th>')
420|     pg.add(f'<td class="LineRight">{runs_9[0]}</td>')
421|     pg.add(f'<td>{runs_9[1]}</td>')
422|     pg.add(f'<td>{runs_9[2]}</td>')
423|     pg.add(f'<td class="{clr} LineLeft">{runs_9[1]-runs_9[2]:+d}</td>')
424|     pg.add(f'<td class="{clr} LineLeft">{win_pct(runs_9[1],runs_9[2]):.3f}</td>')
425|     pg.add('</tr>')
426| 
427|     clr = 'Win' if runs_x[2] < runs_x[1] else 'Lose'
428|     pg.add('<tr>')
429|     pg.add('<th>&gt;10 Runs Scored</th>')
430|     pg.add(f'<td class="LineRight">{runs_x[0]}</td>')
431|     pg.add(f'<td>{runs_x[1]}</td>')
432|     pg.add(f'<td>{runs_x[2]}</td>')
433|     pg.add(f'<td class="{clr} LineLeft">{runs_x[1]-runs_x[2]:+d}</td>')
434|     pg.add(f'<td class="{clr} LineLeft">{win_pct(runs_x[1],runs_x[2]):.3f}</td>')
435|     pg.add('</tr>')
436| 
437|     pg.add('<tr><td colspan="5" style="height:4px; background-color:transparent;"></td></tr>')
438| 
439|     clr = 'Win' if rdif_1[2] < rdif_1[1] else 'Lose'
440|     pg.add('<tr>')
441|     pg.add('<th>1-Run Games</th>')
442|     pg.add(f'<td class="LineRight">{rdif_1[0]}</td>')
443|     pg.add(f'<td>{rdif_1[1]}</td>')
444|     pg.add(f'<td>{rdif_1[2]}</td>')
445|     pg.add(f'<td class="{clr} LineLeft">{rdif_1[1]-rdif_1[2]:+d}</td>')
446|     pg.add(f'<td class="{clr} LineLeft">{win_pct(rdif_1[1],rdif_1[2]):.3f}</td>')
447|     pg.add('</tr>')
448| 
449|     clr = 'Win' if rdif_2[2] < rdif_2[1] else 'Lose'
450|     pg.add('<tr>')
451|     pg.add('<th>2-Run Games</th>')
452|     pg.add(f'<td class="LineRight">{rdif_2[0]}</td>')
453|     pg.add(f'<td>{rdif_2[1]}</td>')
454|     pg.add(f'<td>{rdif_2[2]}</td>')
455|     pg.add(f'<td class="{clr} LineLeft">{rdif_2[1]-rdif_2[2]:+d}</td>')
456|     pg.add(f'<td class="{clr} LineLeft">{win_pct(rdif_2[1],rdif_2[2]):.3f}</td>')
457|     pg.add('</tr>')
458| 
459|     clr = 'Win' if rdif_5[2] < rdif_5[1] else 'Lose'
460|     pg.add('<tr>')
461|     pg.add('<th>3- to 5-Run Games</th>')
462|     pg.add(f'<td class="LineRight">{rdif_5[0]}</td>')
463|     pg.add(f'<td>{rdif_5[1]}</td>')
464|     pg.add(f'<td>{rdif_5[2]}</td>')
465|     pg.add(f'<td class="{clr} LineLeft">{rdif_5[1]-rdif_5[2]:+d}</td>')
466|     pg.add(f'<td class="{clr} LineLeft">{win_pct(rdif_5[1],rdif_5[2]):.3f}</td>')
467|     pg.add('</tr>')
468| 
469|     clr = 'Win' if rdif_x[2] < rdif_x[1] else 'Lose'
470|     pg.add('<tr>')
471|     pg.add('<th>6-Run+ Games</th>')
472|     pg.add(f'<td class="LineRight">{rdif_x[0]}</td>')
473|     pg.add(f'<td>{rdif_x[1]}</td>')
474|     pg.add(f'<td>{rdif_x[2]}</td>')
475|     pg.add(f'<td class="{clr} LineLeft">{rdif_x[1]-rdif_x[2]:+d}</td>')
476|     pg.add(f'<td class="{clr} LineLeft">{win_pct(rdif_x[1],rdif_x[2]):.3f}</td>')
477|     pg.add('</tr>')
478| 
479|     pg.add('</tbody>')
480|     pg.add('</table>')
481| 
482|     # Save the webpage...
483|     pg.save(file_name, log=Log)
484| 
485|     Log.info()
486|     return file_name
487| 
488| ##================================================================================================##
489| def do_season_games_webpage (**kwargs):
490|     '''CMND: Create a webpage listing all games in the season.'''
491|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
492|     fname = KWARG('fname', '{tcode}-{year}-games.html', str, kwargs)
493|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
494|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
495|     team_name = defs.MlbTeams[tcode][2]
496|     team_city = defs.MlbTeams[tcode][3]
497|     file_name = path.join(fpath,fname) if fpath else fname
498|     file_name = file_name.format(**locals())
499|     Log.info(f'season-games-webpage:: {list(kwargs.keys())}')
500|     Log.debug(f'{fpath=}')
501|     Log.debug(f'{fname=}')
502|     Log.debug(f'{tcode=}')
503|     Log.debug(f'{year=}')
504|     Log.debug(f'{team_name=}')
505|     Log.debug(f'{file_name=}')
506|     Log.info()
507| 
508|     # Extract data from team's season...
509|     season_data = defs.CsvTeamGames(tcode)
510|     batting_data = defs.CsvTeamGamesBatting(tcode)
511|     pitching_data = defs.CsvTeamGamesPitching(tcode)
512|     pitchers = pitching_data.get_column_data(-1)
513| 
514|     game_data = [marker(start=1, dtype=int)]                    # 0
515|     game_data.append( season_data.get_column_data('Date') )     # 1
516|     game_data.append( season_data.get_column_data('Opp') )      # 2
517|     game_data.append( season_data.get_column_data(4) )          # 3
518|     game_data.append( batting_data.get_column_data('Rslt') )    # 4
519|     game_data.append( season_data.get_column_data('W-L') )      # 5
520|     game_data.append( season_data.get_column_data_int('R') )    # 6
521|     game_data.append( season_data.get_column_data_int('RA') )   # 7
522|     game_data.append( batting_data.get_column_data_int('H') )   # 8
523|     game_data.append( pitching_data.get_column_data_int('H') )  # 9
524|     game_data.append( batting_data.get_column_data_int('HR') )  # 10
525|     game_data.append( batting_data.get_column_data_int('SO') )  # 11
526|     game_data.append( batting_data.get_column_data_int('BB') )  # 12
527|     game_data.append( [p[0:p.index('(')] for p in pitchers] )   # 13
528|     game_data.append( pitching_data.get_column_data_int('HR') ) # 14
529|     game_data.append( pitching_data.get_column_data_int('SO') ) # 15
530|     game_data.append( pitching_data.get_column_data_int('BB') ) # 16
531| 
532|     props = dict(
533|         h1 = f'Baseball {year}',
534|         h2 = f'{team_city} {team_name}',
535|         h3 = f'{team_name} Games {year}',
536|         css = ['/basic.css'],
537|         csstxt = SeasonGamesCSS
538|     )
539|     pg = WebPage(f'{team_city} {team_name} Games {year}', **props)
540| 
541|     pg.add('<table>')
542| 
543|     # Header...
544|     pg.add('<thead>')
545|     pg.add('<tr>')
546|     pg.add('<th>#</th>')
547|     pg.add('<th>Date</th>')
548|     pg.add('<th></th>')
549|     pg.add('<th>Opps</th>')
550|     pg.add('<th>WL</th>')
551|     pg.add('<th>WL%</th>')
552|     pg.add('<th>R</th>')
553|     pg.add('<th>r</th>')
554|     pg.add('<th>H</th>')
555|     pg.add('<th>h</th>')
556|     pg.add('<th>HR</th>')
557|     pg.add('<th>SO</th>')
558|     pg.add('<th>BB</th>')
559|     pg.add('<th>R&Delta;</th>')
560|     pg.add('<th>H&Delta;</th>')
561|     pg.add('<th>R/H</th>')
562|     pg.add('<th>Starter</th>')
563|     pg.add('<th>hr</th>')
564|     pg.add('<th>so</th>')
565|     pg.add('<th>bb</th>')
566|     pg.add('</tr>')
567|     pg.add('</thead>')
568| 
569|     # Footer...
570|     pg.add('<tfoot>')
571|     pg.add('<tr>')
572|     pg.add('<th>#</th>')
573|     pg.add('<th>Date</th>')
574|     pg.add('<th></th>')
575|     pg.add('<th>Opps</th>')
576|     pg.add('<th>WL</th>')
577|     pg.add('<th>WL%</th>')
578|     pg.add('<th>R</th>')
579|     pg.add('<th>r</th>')
580|     pg.add('<th>H</th>')
581|     pg.add('<th>h</th>')
582|     pg.add('<th>HR</th>')
583|     pg.add('<th>SO</th>')
584|     pg.add('<th>BB</th>')
585|     pg.add('<th>R&Delta;</th>')
586|     pg.add('<th>H&Delta;</th>')
587|     pg.add('<th>R/H</th>')
588|     pg.add('<th>Starter</th>')
589|     pg.add('<th>hr</th>')
590|     pg.add('<th>so</th>')
591|     pg.add('<th>bb</th>')
592|     pg.add('</tr>')
593|     pg.add('</tfoot>')
594| 
595|     # Data...
596|     pg.add('<tbody>')
597| 
598|     series_runs_scored  = 0
599|     series_runs_allowed = 0
600|     series_hits_scored  = 0
601|     series_hits_allowed = 0
602|     series_hr_scored    = 0
603|     series_hr_allowed   = 0
604|     series_so_scored    = 0
605|     series_so_allowed   = 0
606|     series_bb_scored    = 0
607|     series_bb_allowed   = 0
608|     series_wins         = 0
609|     series_losses       = 0
610| 
611|     season_runs_scored  = 0
612|     season_runs_allowed = 0
613|     season_hits_scored  = 0
614|     season_hits_allowed = 0
615|     season_hr_scored    = 0
616|     season_hr_allowed   = 0
617|     season_so_scored    = 0
618|     season_so_allowed   = 0
619|     season_bb_scored    = 0
620|     season_bb_allowed   = 0
621|     season_wins         = 0
622|     season_losses       = 0
623| 
624|     curr_opp = game_data[2][0]
625|     curr_loc = game_data[3][0]
626| 
627|     def series_summary ():
628|         """Output series stats."""
629| 
630|         def won_tied_lost ():
631|             """Label series as won!, lost, or tied. Return text and CSS class."""
632|             total_games = series_wins + series_losses
633|             if series_wins == total_games: return ('sweep!', 'Win')
634|             if series_losses == total_games: return ('swept', 'Lose')
635|             if series_losses < series_wins: return ('won!', 'Win')
636|             if series_wins < series_losses: return ('lost', 'Lose')
637|             return ('tied', 'Tie')
638| 
639|         txt,clr = won_tied_lost()
640|         run_diff = series_runs_scored - series_runs_allowed
641|         hit_diff = series_hits_scored - series_hits_allowed
642|         runs_hit = series_runs_scored / series_hits_scored
643|         pg.add('<tr>')
644|         pg.add(f'<td class="LineTop " colspan="2">Series ({txt}):</td>')
645|         pg.add(f'<td class="LineTop type">{curr_loc}</td>')
646|         pg.add(f'<td class="LineTop name LineRight">{curr_opp}</td>')
647|         pg.add(f'<td class="LineTop LineRight score {clr}">{series_wins}-{series_losses}</td>')
648|         pg.add(f'<td class="LineTop LineRight"></td>')
649|         pg.add(f'<td class="LineTop runs">{series_runs_scored}</td>')
650|         pg.add(f'<td class="LineTop runs LineRight">{series_runs_allowed}</td>')
651|         pg.add(f'<td class="LineTop hits">{series_hits_scored}</td>')
652|         pg.add(f'<td class="LineTop hits LineRight">{series_hits_allowed}</td>')
653|         pg.add(f'<td class="LineTop hits">{series_hr_scored}</td>')
654|         pg.add(f'<td class="LineTop hits">{series_so_scored}</td>')
655|         pg.add(f'<td class="LineTop hits LineRight">{series_bb_scored}</td>')
656|         pg.add(f'<td class="LineTop runs">{run_diff:+d}</td>')
657|         pg.add(f'<td class="LineTop LineRight hits">{hit_diff:+d}</td>')
658|         pg.add(f'<td class="LineTop LineRight">{runs_hit:.3f}</td>')
659|         pg.add(f'<td class="LineTop LineRight"></td>')
660|         pg.add(f'<td class="LineTop hits">{series_hr_allowed}</td>')
661|         pg.add(f'<td class="LineTop hits">{series_so_allowed}</td>')
662|         pg.add(f'<td class="LineTop hits">{series_bb_allowed}</td>')
663|         pg.add('</tr>')
664|         pg.add('<tr><td colspan="20" style="height:7px;" class="LineBot"></td></tr>')
665| 
666|     # For each row of data...
667|     for ix,dt,opp,loc,res,wl,rs,ra,hs,ha,hr,so,bb,pit,hra,soa,bba in zip(*game_data):
668|         Log.trace(f'{ix:3d}: {dt} {loc}{opp} {rs}-{ra}')
669|         clr = 'Win' if res == 'W' else 'Lose'
670| 
671|         # If a new opponent this row, summaries the previous series...
672|         if opp != curr_opp:
673|             # Do series summary...
674|             series_summary()
675| 
676|             # Reset counters for this series...
677|             series_runs_scored  = 0
678|             series_runs_allowed = 0
679|             series_hits_scored  = 0
680|             series_hits_allowed = 0
681|             series_wins         = 0
682|             series_losses       = 0
683|             series_hr_scored    = 0
684|             series_hr_allowed   = 0
685|             series_so_scored    = 0
686|             series_so_allowed   = 0
687|             series_bb_scored    = 0
688|             series_bb_allowed   = 0
689|             curr_loc            = loc
690|             curr_opp            = opp
691| 
692|         # Add stats to counters...
693|         series_runs_scored  += rs
694|         series_runs_allowed += ra
695|         series_hits_scored  += hs
696|         series_hits_allowed += ha
697|         series_hr_scored    += hr
698|         series_hr_allowed   += hra
699|         series_so_scored    += so
700|         series_so_allowed   += soa
701|         series_bb_scored    += bb
702|         series_bb_allowed   += bba
703|         series_wins         += (1 if res == 'W' else 0)
704|         series_losses       += (0 if res == 'W' else 1)
705| 
706|         season_runs_scored  += rs
707|         season_runs_allowed += ra
708|         season_hits_scored  += hs
709|         season_hits_allowed += ha
710|         season_hr_scored    += hr
711|         season_hr_allowed   += hra
712|         season_so_scored    += so
713|         season_so_allowed   += soa
714|         season_bb_scored    += bb
715|         season_bb_allowed   += bba
716|         season_wins         += (1 if res == 'W' else 0)
717|         season_losses       += (0 if res == 'W' else 1)
718| 
719|         # Write game stats row...
720|         pg.add('<tr>')
721|         pg.add(f'<th>{ix}</th>')
722|         pg.add(f'<td class="date LineRight">{dt}</td>')
723|         pg.add(f'<td class="type">{loc}</td>')
724|         pg.add(f'<td class="name LineRight">{opp}</td>')
725|         pg.add(f'<td class="score">{wl}</td>')
726|         pg.add(f'<td class="LineRight">{season_wins/ix:.3f}</td>')
727|         pg.add(f'<td class="runs {clr}">{rs}</td>')
728|         pg.add(f'<td class="runs LineRight {clr}">{ra}</td>')
729|         pg.add(f'<td class="hits">{hs}</td>')
730|         pg.add(f'<td class="hits LineRight">{ha}</td>')
731|         pg.add(f'<td class="hits">{hr}</td>')
732|         pg.add(f'<td class="hits">{so}</td>')
733|         pg.add(f'<td class="hits LineRight">{bb}</td>')
734|         pg.add(f'<td class="runs">{rs-ra:+d}</td>')
735|         pg.add(f'<td class="hits LineRight">{hs-ha:+d}</td>')
736|         pg.add(f'<td class="LineRight">{rs/hs:.3f}</td>')
737|         pg.add(f'<td class="LineRight">{pit}</td>')
738|         pg.add(f'<td class="hits">{hra}</td>')
739|         pg.add(f'<td class="hits">{soa}</td>')
740|         pg.add(f'<td class="hits">{bba}</td>')
741|         pg.add('</tr>')
742|     Log.trace()
743| 
744|     # Do series summary...
745|     series_summary()
746| 
747|     # Do season summary...
748|     run_diff = season_runs_scored - season_runs_allowed
749|     hit_diff = season_hits_scored - season_hits_allowed
750|     runs_hit = season_runs_scored / season_hits_scored
751|     sea_clr = 'Win' if (season_losses < season_wins) else 'Lose'
752|     run_clr = 'Win' if (season_runs_allowed < season_runs_scored) else 'Lose'
753|     hit_clr = 'Win' if (season_hits_allowed < season_hits_scored) else 'Lose'
754|     pg.add('<tr>')
755|     pg.add('<td class="LineTop LineBot name" colspan="4">Season:</td>')
756|     pg.add(f'<td class="LineTop LineBot score {sea_clr}">{wl}</td>')
757|     pg.add(f'<td class="LineTop LineBot LineRight score {sea_clr}">{season_wins/ix:.3f}</td>')
758|     pg.add(f'<td class="LineTop LineBot runs {run_clr}">{season_runs_scored}</td>')
759|     pg.add(f'<td class="LineTop LineBot LineRight runs {run_clr}">{season_runs_allowed}</td>')
760|     pg.add(f'<td class="LineTop LineBot runs {hit_clr}">{season_hits_scored}</td>')
761|     pg.add(f'<td class="LineTop LineBot LineRight runs {hit_clr}">{season_hits_allowed}</td>')
762|     pg.add(f'<td class="LineTop LineBot runs">{season_hr_scored}</td>')
763|     pg.add(f'<td class="LineTop LineBot runs">{season_so_scored}</td>')
764|     pg.add(f'<td class="LineTop LineBot runs LineRight">{season_bb_scored}</td>')
765|     pg.add(f'<td class="LineTop LineBot runs">{run_diff:+d}</td>')
766|     pg.add(f'<td class="LineTop LineBot LineRight runs">{hit_diff:+d}</td>')
767|     pg.add(f'<td class="LineTop LineBot LineRight score">{runs_hit:.3f}</td>')
768|     pg.add(f'<td class="LineTop LineBot LineRight"></td>')
769|     pg.add(f'<td class="LineTop LineBot runs">{season_hr_allowed}</td>')
770|     pg.add(f'<td class="LineTop LineBot runs">{season_so_allowed}</td>')
771|     pg.add(f'<td class="LineTop LineBot runs">{season_bb_allowed}</td>')
772|     pg.add('</tr>')
773| 
774|     pg.add('</tbody>')
775|     pg.add('</table>')
776| 
777|     # Save the webpage...
778|     pg.save(file_name, log=Log)
779| 
780|     Log.info()
781|     return file_name
782| 
783| ##================================================================================================##
784| def do_test (**kwargs):
785|     '''CMND: Do a test.'''
786|     fpath = KWARG('fpath', defs.BasePath, str, kwargs)
787|     fname = KWARG('fname', 'test-{tcode}-{year}.png', str, kwargs)
788|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
789|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
790|     team_name = defs.MlbTeams[tcode][2]
791|     file_name = path.join(fpath,fname) if fpath else fname
792|     file_name = file_name.format(**locals())
793|     Log.info(f'test:: {list(kwargs.keys())}')
794|     Log.debug(f'{fpath=}')
795|     Log.debug(f'{fname=}')
796|     Log.debug(f'{tcode=}')
797|     Log.debug(f'{year=}')
798|     Log.debug(f'{team_name=}')
799|     Log.debug(f'{file_name=}')
800|     Log.info()
801| 
802|     # Extract data from team's season...
803|     csv_data = defs.CsvTeamGames(tcode)
804| 
805|     Log.info()
806|     return file_name
807| 
808| ####################################################################################################
809| def dispatch (cmd, **kwargs):
810|     '''Dispatch to a module function based on CMD.'''
811|     Log.info(f'CMD: {cmd}')
812|     for kw in kwargs:
813|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
814|     Log.info()
815| 
816|     if cmd == 'stats': return do_season_stats_webpage   (**kwargs)
817|     if cmd == 'games': return do_season_games_webpage   (**kwargs)
818|     if cmd == 'test':  return do_test                   (**kwargs)
819| 
820|     return 'Nothing to do!'
821| ####################################################################################################
822| if __name__ == '__main__':
823|     print(f'autorun: {argv[0]}')
824|     Log.start(path.join(defs.BasePath,'games.log'))
825|     Log.level(trace())
826|     Log.info(argv[0])
827|     cmd = argv[1] if 1 < len(argv) else CMND
828|     kwargs = ARGS
829|     for a in argv[2:]:
830|         nv = a.split('=', 1)
831|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
832|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
833|     Log.info()
834|     try:
835|         print(f'CMD: {cmd}')
836|         print()
837|         obj = dispatch(cmd, **kwargs)
838|         print(obj)
839|         print()
840|         Log.info(obj)
841|         Log.info()
842|     except:
843|         etype, evalue, tb = exc_info()
844|         ts = extract_tb(tb)
845|         Log.error()
846|         Log.error(f'{etype.__name__}: {evalue!s}')
847|         Log.error()
848|         for t in ts[-5:]:
849|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
850|             Log.error(f' {t[3]}')
851|             Log.error()
852|         raise
853|     finally:
854|         Log.end()
855| ####################################################################################################
856| '''eof'''
857|