Syntrex commited on
Commit
07beb1d
Β·
verified Β·
1 Parent(s): 3aee7f5

Update SQL

Browse files
Files changed (1) hide show
  1. SQL +310 -11
SQL CHANGED
@@ -1,20 +1,319 @@
1
- SELECT COUNT(*) AS core_rows FROM statcast_event_core;
 
 
 
2
 
3
- SELECT COUNT(*) AS release_rows FROM statcast_pitch_release;
 
4
 
5
- SELECT COUNT(*) AS plate_rows FROM statcast_plate_location;
6
 
7
- SELECT COUNT(*) AS batted_ball_rows FROM statcast_batted_ball;
8
 
9
- SELECT COUNT(*) AS bat_tracking_rows FROM statcast_bat_tracking;
 
10
 
11
- SELECT COUNT(*) AS score_rows FROM statcast_score_context;
12
 
13
- SELECT COUNT(*) AS fielding_rows FROM statcast_fielding_context;
 
 
 
14
 
15
- SELECT COUNT(*) AS player_meta_rows FROM statcast_player_meta;
16
 
17
- SELECT COUNT(*) AS legacy_rows FROM statcast_legacy_misc;
 
 
18
 
19
- SELECT COUNT(DISTINCT event_key) AS distinct_event_keys
20
- FROM statcast_event_core;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ from sqlalchemy import create_engine, text
3
+ import pandas as pd
4
+ import time
5
 
6
+ DATABASE_URL = "PASTE_YOUR_COCKROACH_CONNECTION_STRING_HERE"
7
+ CHUNK_SIZE = 100_000
8
 
9
+ engine = create_engine(DATABASE_URL, pool_pre_ping=True)
10
 
 
11
 
12
+ def say(msg: str) -> None:
13
+ print(msg, flush=True)
14
 
 
15
 
16
+ def safe_rate(num, den):
17
+ if den is None or den == 0:
18
+ return None
19
+ return num / den
20
 
 
21
 
22
+ def normalize_pitch_family(pitch_name, pitch_type):
23
+ name = str(pitch_name or "").strip().lower()
24
+ ptype = str(pitch_type or "").strip().upper()
25
 
26
+ if name in {
27
+ "4-seam fastball",
28
+ "fastball",
29
+ "2-seam fastball",
30
+ "sinker",
31
+ "cutter",
32
+ "splitter",
33
+ "forkball",
34
+ }:
35
+ return "fastball"
36
+
37
+ if name in {
38
+ "slider",
39
+ "sweeper",
40
+ "curveball",
41
+ "knuckle curve",
42
+ "slurve",
43
+ }:
44
+ return "breaking"
45
+
46
+ if name in {
47
+ "changeup",
48
+ "circle change",
49
+ "screwball",
50
+ "eephus",
51
+ }:
52
+ return "offspeed"
53
+
54
+ if ptype in {"FF", "FT", "SI", "FC", "FS", "FO"}:
55
+ return "fastball"
56
+ if ptype in {"SL", "ST", "SV", "KC", "CU", "CS"}:
57
+ return "breaking"
58
+ if ptype in {"CH", "SC", "EP"}:
59
+ return "offspeed"
60
+
61
+ return "unknown"
62
+
63
+
64
+ def classify_zone_bucket(zone_value):
65
+ try:
66
+ z = float(zone_value)
67
+ except Exception:
68
+ return "unknown"
69
+
70
+ if z in {1, 2, 3, 4, 5, 6, 7, 8, 9}:
71
+ return "heart"
72
+ if z in {11, 12, 13, 14}:
73
+ return "shadow"
74
+ if z in {15, 16, 17, 18, 19, 20}:
75
+ return "chase"
76
+ if z in {21, 22, 23, 24, 25, 26, 27, 28}:
77
+ return "waste"
78
+
79
+ return "unknown"
80
+
81
+
82
+ def is_whiff(description):
83
+ d = str(description or "").strip().lower()
84
+ return int(d in {"swinging_strike", "swinging_strike_blocked"})
85
+
86
+
87
+ def is_called_strike(description):
88
+ d = str(description or "").strip().lower()
89
+ return int(d == "called_strike")
90
+
91
+
92
+ def is_ball_in_play(description):
93
+ d = str(description or "").strip().lower()
94
+ return int(d == "hit_into_play")
95
+
96
+
97
+ def is_hit(events):
98
+ e = str(events or "").strip().lower()
99
+ return int(e in {"single", "double", "triple", "home_run"})
100
+
101
+
102
+ def is_hr(events):
103
+ e = str(events or "").strip().lower()
104
+ return int(e == "home_run")
105
+
106
+
107
+ def is_damage(launch_speed, launch_angle, xwoba):
108
+ try:
109
+ ev = float(launch_speed) if launch_speed is not None and not pd.isna(launch_speed) else None
110
+ la = float(launch_angle) if launch_angle is not None and not pd.isna(launch_angle) else None
111
+ xw = float(xwoba) if xwoba is not None and not pd.isna(xwoba) else None
112
+ except Exception:
113
+ return 0
114
+
115
+ # same conservative damage logic we discussed
116
+ if ev is not None and la is not None and ev >= 98 and 26 <= la <= 30:
117
+ return 1
118
+ if xw is not None and xw >= 0.600:
119
+ return 1
120
+ return 0
121
+
122
+
123
+ say("πŸš€ Booting the Family + Zone Arsenal Factory...")
124
+ time.sleep(0.4)
125
+ say("⚾ Rolling out scouting reports, sunflower seeds, and deeply held slider opinions...")
126
+ time.sleep(0.4)
127
+ say("🧠 Teaching the model that a fastball in the heart is not the same as one in the shadow...")
128
+ time.sleep(0.4)
129
+ say("🐻 Somewhere, a Cubs hitter is politely rolling over a slider off the plate...")
130
+ time.sleep(0.4)
131
+
132
+ query = """
133
+ SELECT
134
+ e.event_key,
135
+ e.batter,
136
+ e.pitcher,
137
+ e.pitch_type,
138
+ e.pitch_name,
139
+ e.zone,
140
+ e.description,
141
+ e.events,
142
+ b.launch_speed,
143
+ b.launch_angle,
144
+ b.estimated_woba_using_speedangle
145
+ FROM statcast_event_core e
146
+ LEFT JOIN statcast_batted_ball b
147
+ ON e.event_key = b.event_key
148
+ """
149
+
150
+ pitcher_acc = defaultdict(
151
+ lambda: {
152
+ "sample_size": 0,
153
+ "whiff_count": 0,
154
+ "called_strike_count": 0,
155
+ "ball_in_play_count": 0,
156
+ "hit_allowed_count": 0,
157
+ "hr_allowed_count": 0,
158
+ "damage_allowed_count": 0,
159
+ "launch_speed_sum": 0.0,
160
+ "launch_speed_count": 0,
161
+ "launch_angle_sum": 0.0,
162
+ "launch_angle_count": 0,
163
+ "xwoba_sum": 0.0,
164
+ "xwoba_count": 0,
165
+ }
166
+ )
167
+
168
+ batter_acc = defaultdict(
169
+ lambda: {
170
+ "sample_size": 0,
171
+ "whiff_count": 0,
172
+ "called_strike_count": 0,
173
+ "ball_in_play_count": 0,
174
+ "hit_count": 0,
175
+ "hr_count": 0,
176
+ "damage_count": 0,
177
+ "launch_speed_sum": 0.0,
178
+ "launch_speed_count": 0,
179
+ "launch_angle_sum": 0.0,
180
+ "launch_angle_count": 0,
181
+ "xwoba_sum": 0.0,
182
+ "xwoba_count": 0,
183
+ }
184
+ )
185
+
186
+ pitcher_family_totals = defaultdict(int)
187
+ pitcher_overall_totals = defaultdict(int)
188
+
189
+ chunk_num = 0
190
+ total_rows = 0
191
+
192
+ conn = engine.connect().execution_options(stream_results=True)
193
+
194
+ try:
195
+ say("πŸ¦€ Asking Cockroach for chunks instead of trying to eat the whole buffet at once...")
196
+ for chunk in pd.read_sql_query(text(query), conn, chunksize=CHUNK_SIZE):
197
+ chunk_num += 1
198
+ total_rows += len(chunk)
199
+
200
+ say(f"\nπŸ“¦ Chunk {chunk_num} arrived with {len(chunk):,} rows | total seen: {total_rows:,}")
201
+ say("🎯 Sorting pitches into families and zones like an overcaffeinated front office analyst...")
202
+ say("πŸ“‹ Updating scouting reports and pretending the Cubs are still working on two-strike adjustments...")
203
+
204
+ for row in chunk.itertuples(index=False):
205
+ batter = row.batter
206
+ pitcher = row.pitcher
207
+ pitch_type = row.pitch_type
208
+ pitch_name = row.pitch_name
209
+ zone = row.zone
210
+ description = row.description
211
+ events = row.events
212
+ launch_speed = row.launch_speed
213
+ launch_angle = row.launch_angle
214
+ xwoba = row.estimated_woba_using_speedangle
215
+
216
+ if pitch_type is None and pitch_name is None:
217
+ continue
218
+
219
+ pitch_family = normalize_pitch_family(pitch_name, pitch_type)
220
+ zone_bucket = classify_zone_bucket(zone)
221
+
222
+ if pitch_family == "unknown" or zone_bucket == "unknown":
223
+ continue
224
+
225
+ # -----------------------------------------
226
+ # PITCHER FAMILY + ZONE
227
+ # -----------------------------------------
228
+ if pitcher is not None and not pd.isna(pitcher):
229
+ pitcher = int(pitcher)
230
+ pkey = (pitcher, pitch_family, zone_bucket)
231
+ p = pitcher_acc[pkey]
232
+
233
+ p["sample_size"] += 1
234
+ p["whiff_count"] += is_whiff(description)
235
+ p["called_strike_count"] += is_called_strike(description)
236
+ p["ball_in_play_count"] += is_ball_in_play(description)
237
+ p["hit_allowed_count"] += is_hit(events)
238
+ p["hr_allowed_count"] += is_hr(events)
239
+ p["damage_allowed_count"] += is_damage(launch_speed, launch_angle, xwoba)
240
+
241
+ if launch_speed is not None and not pd.isna(launch_speed):
242
+ p["launch_speed_sum"] += float(launch_speed)
243
+ p["launch_speed_count"] += 1
244
+
245
+ if launch_angle is not None and not pd.isna(launch_angle):
246
+ p["launch_angle_sum"] += float(launch_angle)
247
+ p["launch_angle_count"] += 1
248
+
249
+ if xwoba is not None and not pd.isna(xwoba):
250
+ p["xwoba_sum"] += float(xwoba)
251
+ p["xwoba_count"] += 1
252
+
253
+ pitcher_family_totals[(pitcher, pitch_family)] += 1
254
+ pitcher_overall_totals[pitcher] += 1
255
+
256
+ # -----------------------------------------
257
+ # BATTER FAMILY + ZONE
258
+ # -----------------------------------------
259
+ if batter is not None and not pd.isna(batter):
260
+ batter = int(batter)
261
+ bkey = (batter, pitch_family, zone_bucket)
262
+ b = batter_acc[bkey]
263
+
264
+ b["sample_size"] += 1
265
+ b["whiff_count"] += is_whiff(description)
266
+ b["called_strike_count"] += is_called_strike(description)
267
+ b["ball_in_play_count"] += is_ball_in_play(description)
268
+ b["hit_count"] += is_hit(events)
269
+ b["hr_count"] += is_hr(events)
270
+ b["damage_count"] += is_damage(launch_speed, launch_angle, xwoba)
271
+
272
+ if launch_speed is not None and not pd.isna(launch_speed):
273
+ b["launch_speed_sum"] += float(launch_speed)
274
+ b["launch_speed_count"] += 1
275
+
276
+ if launch_angle is not None and not pd.isna(launch_angle):
277
+ b["launch_angle_sum"] += float(launch_angle)
278
+ b["launch_angle_count"] += 1
279
+
280
+ if xwoba is not None and not pd.isna(xwoba):
281
+ b["xwoba_sum"] += float(xwoba)
282
+ b["xwoba_count"] += 1
283
+
284
+ say("πŸ”₯ Chunk finished. Another 100k pitches survived arbitration.")
285
+ say("🐻 Cubs update: still late on velocity, still blaming the wind.")
286
+
287
+ finally:
288
+ conn.close()
289
+
290
+ say("\n🧩 Combining the family-zone chaos into something the model can actually use...")
291
+
292
+ pitcher_rows = []
293
+ for (pitcher, pitch_family, zone_bucket), p in pitcher_acc.items():
294
+ sample_size = p["sample_size"]
295
+ fam_total = pitcher_family_totals[(pitcher, pitch_family)]
296
+ overall_total = pitcher_overall_totals[pitcher]
297
+
298
+ pitcher_rows.append(
299
+ {
300
+ "pitcher_id": pitcher,
301
+ "pitch_family": pitch_family,
302
+ "zone_bucket": zone_bucket,
303
+ "sample_size": sample_size,
304
+ "usage_rate_within_family": safe_rate(sample_size, fam_total),
305
+ "usage_rate_overall": safe_rate(sample_size, overall_total),
306
+ "whiff_rate": safe_rate(p["whiff_count"], sample_size),
307
+ "called_strike_rate": safe_rate(p["called_strike_count"], sample_size),
308
+ "ball_in_play_rate": safe_rate(p["ball_in_play_count"], sample_size),
309
+ "hit_allowed_rate": safe_rate(p["hit_allowed_count"], sample_size),
310
+ "hr_allowed_rate": safe_rate(p["hr_allowed_count"], sample_size),
311
+ "damage_allowed_rate": safe_rate(p["damage_allowed_count"], sample_size),
312
+ "avg_launch_speed_allowed": safe_rate(p["launch_speed_sum"], p["launch_speed_count"]),
313
+ "avg_launch_angle_allowed": safe_rate(p["launch_angle_sum"], p["launch_angle_count"]),
314
+ "xwoba_allowed": safe_rate(p["xwoba_sum"], p["xwoba_count"]),
315
+ }
316
+ )
317
+
318
+ batter_rows = []
319
+ for (b