Appendix B — golfkit Reference
golfkit is the Python toolkit behind every number in this book. It lives in toolkit/golfkit/, and every chapter script reaches it through the standard header (Appendix A, §A.9):
import sys; from pathlib import Path
BOOK = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(BOOK / "toolkit")); sys.path.insert(0, str(BOOK / "project"))
from golfkit import style; style.use()
This appendix is a reference, not a tutorial. For each module it gives the purpose, the key functions with their signatures and units, a short example with its real output, and the module's limits. The chapters teach the ideas; come here when you need the exact call.
How this reference was checked. Every signature below was read from the code with inspect.signature (appendices/_code/appendix_b/00_dump_signatures.py prints them all), not copied from older notes. Every example is an excerpt of one of four scripts in appendices/_code/appendix_b/ (01_area1_examples.py, 02_area2_examples.py, 03_area3_examples.py, 04_known_limits.py), and every output block is pasted from running them. The excerpts assume that script's header and imports. Long default arguments are shortened to ... in the signatures; help(function) shows them in full.
B.1 The Map
golfkit has 19 modules in three areas, plus the chart style. Each area produces a different kind of number, and the book labels every number by its kind.
| Area | Modules | Kind of number | Label in the book |
|---|---|---|---|
| 1. Data and professional golf | data, sgtotal, ratings, predict, betting, dfs |
REAL: ESPN PGA TOUR hole-by-hole scores, 2004–2026 | "Data: ESPN PGA TOUR hole-by-hole scores, 2004–2026 (golfkit)" |
| 2. Shots, strokes gained, strategy | baselines, holes, shotsim, sg, dispersion, targeting, markov, whs |
SIMULATED shots, priced with Broadie's published PGA TOUR baseline or a simulated amateur baseline | "SIMULATED — golfkit.shotsim, seed N" |
| 3. Physics | flight, impact, putting, weather, biomech |
Model outputs, validated against published TrackMan data | "golfkit model" |
| Chart style | style |
— | — |
Two rules follow from that table. A simulated category number is never a real player's number: ESPN publishes scores, not shots, so strokes gained by category (OTT, APP, ARG, PUTT) in this book always comes from simulated shots. And a model number is a model's: the flight model's carry for a launch is what the physics predicts, not a measurement.
Conventions shared by all modules
| Quantity | Unit or convention |
|---|---|
| Full shots, distances to the hole off the green | yards |
| Putts, distances on the green, proximity | feet |
| Club and ball speed | mph (the physics modules work internally in m/s) |
| Spin | rpm |
| Angles | degrees |
| Temperature | °F |
| Lateral direction | + = right (a right-handed golfer's slice side); spin axis + = fade or slice (TrackMan sign) |
Hole coordinates (holes, targeting, shotsim) |
yards, tee at (0, 0), x downrange, y lateral (+ right) |
Wind direction from_deg |
0 = headwind, 90 = from the right, 180 = tailwind, 270 = from the left |
| Strokes gained | strokes; positive = better than the baseline |
| Years | calendar year of an event's end date (year), never ESPN's wrap-around season |
⚠️ Common Pitfall: two club-naming schemes The shot simulator names clubs
D 3W 5W HY 4i 5i 6i 7i 8i 9i PW GW SW LW(plusP, the putter). The physics modules (impact,weather,biomech) use TrackMan's names:"Driver","3-wood","7-iron","PW". Passing"7i"toweather.plays_likeor"7-iron"to aGolferwon't do what you mean.
Area 1 — Data and Professional Golf (REAL)
B.2 golfkit.data
Purpose. Loaders and lookups for the ESPN PGA TOUR snapshot in data/processed/. Every loader returns a copy, so you can't damage the cached tables. Appendix C documents every table, column and flag.
| Function | Returns |
|---|---|
load(name) |
One raw processed table, unfiltered: "events", "courses", "players", "player_events", "rounds", "holes" or "player_stats" |
events(seasons=None, years=None, majors_only=False, exclude_multicourse=False, exclude_opposite_field=False, stroke_play_only=True, event_ids=None) |
Events with the derived flags (year, stroke_play_ok, multicourse, opposite_field, quality_ok, par_ok, cut columns …) |
rounds(..., complete_only=True, with_names=False) |
Player-rounds (same event filters as events) with course_round, date, year, season, event_name, major |
holes(event_ids=None, seasons=None, years=None, **event_filters) |
Hole scores: strokes, par. 7.5 million rows unfiltered, so filter when you can |
courses(event_ids=None, **event_filters) |
Par and yards per hole for each course of the selected events |
players() |
player_id (ESPN athlete id, a string), name, country |
player_events(**event_filters) |
One row per (event, player), with the build's columns and the corrected outcomes status_fixed, position_fixed, won_fixed, made_cut_fixed, total_fixed |
player_stats(**event_filters) |
ESPN per-event player statistics, 2015 onward |
event_lookup(name_substring, season=None, year=None, stroke_play_only=False) |
Events whose name contains the text (case-insensitive) |
player_lookup(name_substring), player_id(name) |
Matching players / one ESPN id |
hole_scoring(event_id=None, course_name=None, seasons=None, years=None, by_event=True) |
Per hole: par, yards, n, avg, to_par, p_eagle_or_better, p_birdie, p_par, p_bogey, p_double_plus. Excludes par_ok-flagged events automatically |
course_round_key(rounds) |
The canonical course-round id "<event_id>:<round>:<signature group>" |
infer_cuts(rounds=None, events_df=None) |
Per event: has_cut, cut_round, n_made_cut, cut_line, second cut |
inventory(), inventory_by_season(by="year"), inventory_markdown() |
Exact counts of the snapshot |
Example (01_area1_examples.py):
inv = data.inventory()
print({k: inv[k] for k in ("events", "events_stroke_play_ok", "rounds_complete", "holes", "players")})
ev = data.event_lookup("Masters", year=2026)
eid = ev["event_id"].iloc[0]
pe = data.player_events(event_ids=[eid])
top = pe[pe["position_fixed"] <= 2].sort_values("position_fixed")
names = data.players().set_index("player_id")["name"]
for _, r in top.iterrows():
print(f" {names[r.player_id]:<15} pos {r.position_fixed:.0f} total {r.total_fixed:.0f} won {r.won_fixed}")
hs = data.hole_scoring(event_id=eid).sort_values("to_par", ascending=False)
print(hs[["hole", "par", "yards", "n", "avg", "to_par"]].head(3).round(3).to_string(index=False))
{'events': 1061, 'events_stroke_play_ok': 1031, 'rounds_complete': 417380, 'holes': 7535490, 'players': 4221}
Rory McIlroy pos 1 total 276 won True
Scottie Scheffler pos 2 total 277 won False
hole par yards n avg to_par
5 4 495.0 290 4.297 0.297
11 4 520.0 290 4.293 0.293
17 4 450.0 290 4.238 0.238
Limits.
- Scores only: no shot locations, lies, clubs, wind or tee times, and no LIV, DP World Tour, Korn Ferry or LPGA hole data.
- Never use the build's raw status, position, won or cut_after_round. Use the *_fixed columns and infer_cuts (Appendix C, §C.3).
- Players are compared only within a course-round (same event, round and course, identified by the hole-par sequence). Two courses with identical par sequences can't be told apart; this happens once, at the 2005 Bob Hope (5 courses, 4 signatures).
- ESPN has no per-round dates. golfkit dates round r as start_date + (r − 1) days (🧪), for ordering and recency weights only.
- player_stats reports 0 for statistics it lacks; treat driveDistAvg == 0 or girPoss == 0 as missing. In some events the statistics cover 3 of 4 rounds, so require girPoss == 18 × rounds before joining them to round-level data.
- The join trap. Inner-joining round-level results onto a filtered events table silently drops rounds. Join metadata from data.load("events"), or use a left join.
B.3 golfkit.sgtotal
Purpose. Real field-adjusted strokes gained: total for every complete round of every usable event, from scores alone.
The model is score = mu[course-round] − (a[player] + d[player, year]) + noise, solved as a ridge-penalised sparse least-squares problem (penalties λ_player = 3 and λ_year = 10). sg_total = course_mu − score: strokes better than an average PGA TOUR player-round of that calendar year would be expected to score on the same course in the same round. Field strength is course_mu − field_avg, so sg_total = raw_sg + field_strength. Chapter 10 derives it.
| Function | Returns |
|---|---|
adjusted_sg(rounds=None, lam_player=3.0, lam_year=10.0, as_of=None, window_years=None, cache=True, return_fit=False) |
One row per round: raw_sg, field_avg, field_n, course_mu, field_strength, sg_total, theta_year, plus keys and date, year, major, score, to_par. Strokes per round. Cached in data/processed/cache/. as_of refits on rounds strictly before a date (no look-ahead) |
raw_sg(rounds) |
Adds field_avg, field_n, raw_sg = field_avg − score |
fit_two_way(rounds, lam_player=3.0, lam_year=10.0, lam_course=1e-06, tol=1e-08, maxiter=5000, x0=None) |
A TwoWayFit (course-round table, player abilities, sigma, runtime) |
fit_info(...) |
Metadata of a cached fit |
event_sg(sg, value="sg_total") |
Per (event, player): rounds, sg_sum, sg_mean |
player_season_table(sg, min_rounds=40, value="sg_total", by="year") |
Season leaderboard: rounds, sg_per_round, sd, se (= SD/√n), name |
hole_sg_by_par(event_ids=None, years=None) |
Raw hole-level SG on par 3s, 4s and 5s per player-event |
validate_split_half(sg), validate_predictive(sg, ...), validate_predictive_strict(...) |
The model's reliability and out-of-sample checks |
Example:
sg = sgtotal.adjusted_sg() # cached table, strokes per round
print(f"rounds in the SG table: {len(sg):,}")
tab = sgtotal.player_season_table(sg, min_rounds=40)
print(tab[tab["year"] == 2025].head(3).round(2).to_string(index=False))
rounds in the SG table: 408,603
year player_id rounds sg_per_round sd se name
2025 9478 84 3.29 2.35 0.26 Scottie Scheffler
2025 3470 58 2.29 2.82 0.37 Rory McIlroy
2025 5539 74 2.17 2.39 0.28 Tommy Fleetwood
Limits.
- SG: Total only. No category split is possible from scores.
- Relative to PGA TOUR fields in the snapshot. A player who left for LIV is rated on his PGA TOUR and major rounds only.
- Abilities move in calendar-year steps inside the model. The ratings layer handles change within a year.
- The full-sample table uses later rounds to place earlier ones (abilities are fitted jointly). For any forecast, use as_of, which refits on earlier rounds only.
B.4 golfkit.ratings
Purpose. Player skill ratings from round-level SG: a decay-weighted average, a Bayesian (normal–normal) skill estimate with an empirically fitted prior, and a golf Elo. Chapter 32 builds and tests them.
| Function | Returns |
|---|---|
decay_weighted(sg, as_of=None, half_life_rounds=40.0, half_life_days=None, value="sg_total", max_age_days=None, min_rounds=1) |
rating, W, n_eff, n_rounds, last_date per player. A round k rounds older than the latest gets weight 0.5^(k/h) |
bayes_skill(sg, as_of=None, half_life_rounds=40.0, half_life_days=None, prior=None, sigma=None, value="sg_total", player_ids=None) |
post_mean, post_sd, prior_mean, xbar, n_eff, n_rounds, name. Strokes per round |
pre_event_ratings(sg, half_life_rounds=40.0, form_rounds=8, value="sg_total") |
Pre-event features for every player-event, with no look-ahead, plus the outcome |
fit_predictive_prior(pe, sigma), estimate_prior(xbar, n_eff, n_prior, sigma), default_prior(sg, as_of=None, ...), posterior(xbar, n_eff, n_prior, prior) |
The prior machinery |
round_sigma(sg, value="sg_total", by_year=True, min_rounds=10) |
Pooled within-player round SD (strokes) |
elo(sg, K=48.0, scale=400.0, init=1500.0, return_pairs_logloss=False) |
(current, history) |
elo_win_prob(r_i, r_j, scale=400.0) |
Probability that i beats j head to head (ties count ½) |
elo_k_scan(...), half_life_scan(...), form_vs_class(...) |
Tuning and validation studies |
plot_trajectory(sg, player_ids, ax=None, ...) |
A rating-trajectory chart in house style |
Example:
b = ratings.bayes_skill(sg, as_of="2026-04-09") # the Thursday of the 2026 Masters
b = b.assign(name=b["player_id"].map(names)).sort_values("post_mean", ascending=False)
print(b[["name", "post_mean", "post_sd", "n_eff"]].head(3).round(2).to_string(index=False))
print(f"Elo: 2097 vs 1937 -> P(head-to-head win) = {ratings.elo_win_prob(2097, 1937):.3f}")
name post_mean post_sd n_eff
Scottie Scheffler 2.92 0.4 115.41
Rory McIlroy 2.07 0.4 115.42
Jon Rahm 2.04 0.4 115.41
Elo: 2097 vs 1937 -> P(head-to-head win) = 0.715
Limits.
- post_sd does not widen when a player stops playing. Decay weights count rounds, not days, so a player with few recent rounds keeps the same uncertainty as a regular. Any forecast must widen absent players' uncertainty explicitly. yardbook.forecast.forecast_event(widen=True) does this (Chapter 34).
- Elo is zero-sum within each event and starts every new player at 1500, so newcomers are under-rated until they have played a few events.
B.5 golfkit.predict
Purpose. Monte Carlo tournament simulation, cut rules, calibration tools, the round-variance model and the course-fit test datasets.
| Function or class | Returns |
|---|---|
simulate_tournament(field, n_rounds=4, cut=CutRule(), n_sims=20000, event_sd=0.0, round_sd=2.75, par=72, rng=None, return_sims=False, wd_prob=0.0, wd_round_probs=None) |
player_id, mean, p_win, p_top5, p_top10, p_top20, p_make_cut, exp_position. field needs player_id and mean (expected SG per round, strokes); optional skill_sd, round_sd, wd_prob columns |
CutRule(after_round=2, top_n=65, ties=True, within=None, second_after_round=None, second_top_n=None), NO_CUT |
Cut rules; .describe() |
default_cut_rule(year, cls="regular"), infer_cut_rule(event_id), cut_rule_table() |
Era defaults; the rule inferred from who teed off after the cut |
ModelParams(half_life_rounds=40.0, half_life_days=None, player_sd=False, n_sims=10000, prior_from="2016-01-01", seed=2024) |
Settings for the real-event pipeline |
field_for_event(event_id, sg_asof, prior, params=ModelParams(), psd=None, pooled_round_sd=2.75) |
The simulator's input table for a real event |
predict_event(event_id, params=ModelParams(), n_sims=None, rng=None) |
Pre-event probabilities for a real event, refitted as-of its start, with the real outcome attached (several seconds per event) |
walk_forward(start="2024-01-01", end=None, params=ModelParams(), cache=True, max_events=None) |
Cached walk-forward predictions and outcomes |
brier(p, y), log_loss(p, y, eps=1e-06), reliability_table(p, y, bins=10, strategy="quantile"), calibration_report(wf, markets=...) |
Scoring and calibration |
round_sd_components(sg, prior=None), player_round_sd(sg, as_of=None, years_back=3.0, min_rounds=2) |
The variance model |
withdrawal_rates(before, years=3.0, n_rounds=4) |
Withdrawal probability and timing from real data |
course_features(), course_fit_dataset(...), course_fit_eval(...) |
The course-fit study (Chapter 33) |
plot_probabilities(probs, ...), plot_reliability(table, ...) |
House-style charts |
Example, a toy field of 120 players (one 2.5-stroke favourite, three others above average, 116 average players):
field = pd.DataFrame({"player_id": ["A", "B", "C", "D"] + [f"P{i}" for i in range(116)],
"mean": [2.5, 1.5, 1.0, 0.5] + [0.0] * 116}) # toy field: SG per round
probs = predict.simulate_tournament(field, n_sims=5000, rng=7)
print(probs.head(4)[["player_id", "mean", "p_win", "p_top10", "p_make_cut"]].round(3).to_string(index=False))
print("era default cut 2026 regular:", predict.default_cut_rule(2026).describe())
player_id mean p_win p_top10 p_make_cut
A 2.5 0.225 0.680 0.931
B 1.5 0.070 0.374 0.836
C 1.0 0.030 0.272 0.761
D 0.5 0.012 0.156 0.695
era default cut 2026 regular: top 65 & ties after R2
Even a player 2.5 strokes per round better than an average tour player wins only about one simulated event in four against this field (theme 5).
Limits.
- No course fit, weather or tee-time draw in the simulator.
- Withdrawals are simulated only when you pass wd_prob (walk_forward and predict_event do, at the previous three years' rate).
- Cut rules are inferred from the data, not read from regulations. When the Masters' 10-stroke clause didn't bind, the data can't tell "top 50 and ties" from "top 50 and ties plus anyone within 10".
- Inherits the ratings' absent-player problem (§B.4).
B.6 golfkit.betting
Purpose. Odds arithmetic, margin removal, expected value, Kelly staking and bankroll simulation. There are no real bookmaker odds in this book's data. demo_market builds clearly HYPOTHETICAL prices for teaching (Chapter 36).
| Function | Returns |
|---|---|
american_to_decimal(a), decimal_to_american(d), fractional_to_decimal(frac), decimal_to_fractional(d, max_denominator=100) |
Conversions (vectorised; fractional takes strings like "5/2" or "evens") |
implied_prob(odds, fmt="decimal"), prob_to_decimal(p) |
1/d, including the margin; fair odds for a probability |
overround(decimal_odds, target=1.0) |
Σ 1/d − target (see the known limitation in §B.22) |
devig(decimal_odds, method="proportional", target=1.0) |
Fair probabilities; methods "proportional", "power", "shin" |
shin_z(decimal_odds) |
Shin's estimated insider share |
expected_value(p, decimal_odds, stake=1.0), edge(p, decimal_odds) |
stake·(p·d − 1); p·d − 1 |
kelly(p, decimal_odds), fractional_kelly(p, decimal_odds, fraction=0.5), growth_rate(f, p, decimal_odds) |
Staking |
dead_heat_return(stake, decimal_odds, places_paid, tied, places_left) |
Dead-heat rule payout |
demo_market(p_true, margin=0.2, longshot_bias=1.0, noise_sd=0.0, target=1.0, rng=None) |
HYPOTHETICAL decimal odds |
simulate_bankroll(p_true, decimal_odds, stake_fraction, n_paths=2000, bankroll0=100.0, rng=None, n_rounds=None, cap=1.0) |
Bankroll paths and summaries |
bet_table(p_model, decimal_odds, names=None, kelly_fraction=0.25) |
Price, implied and model probability, edge, EV, Kelly |
Example (the three-way market is hypothetical):
print("+250 ->", betting.american_to_decimal(250), "| -150 ->", round(float(betting.american_to_decimal(-150)), 4))
book = np.array([1.9, 3.1, 4.2]) # a three-way market, decimal odds (hypothetical)
print("overround:", round(betting.overround(book), 4), "| fair probs:", betting.devig(book).round(4))
print("edge at p=0.35, d=3.1:", round(float(betting.edge(0.35, 3.1)), 4),
"| full Kelly:", round(float(betting.kelly(0.35, 3.1)), 4))
+250 -> 3.5 | -150 -> 1.6667
overround: 0.087 | fair probs: [0.4842 0.2968 0.219 ]
edge at p=0.35, d=3.1: 0.085 | full Kelly: 0.0405
Limits. The arithmetic is exact, but an "edge" is only as good as the probability you feed it, and a model's probability has its own error. Verifying a small edge takes thousands of bets (Chapter 36).
B.7 golfkit.dfs
Purpose. Daily-fantasy golf: scoring real hole scores under DraftKings Classic and FanDuel rules, a skill-to-points projection, and an exact lineup optimiser. The scoring rules are parsed from data/reference/dfs_scoring.csv, checked on 2026-11-26 (dfs.RULES_CHECKED). Chapter 37 uses it.
| Function | Returns |
|---|---|
rules(site="DraftKings"), DK_RULES, FD_RULES |
Scoring rules dict: hole points by score relative to par, bonuses, finish table, salary_cap, roster_size |
score_rounds(holes, rule=DK_RULES) |
Per-round fantasy points from hole scores |
score_event(event_id, rule=DK_RULES, with_names=True) |
Per player: round_pts, bonuses, finish_pts, points (playoff holes excluded) |
finish_points(position, rule=DK_RULES) |
Finish points (ties are not averaged) |
fit_projection(events_df, pre, rule=DK_RULES), project(skill, coef) |
Points ≈ a + b·skill + c·skill², fitted on real events |
demo_salaries(field, skill_col="mean", cap=50000, top=11000, bottom=6000, power=1.6, step=100) |
ILLUSTRATIVE salaries, not real prices |
demo_ownership(pool, proj_col="proj", temperature=0.35, roster_size=6) |
ILLUSTRATIVE ownership (a toy softmax) |
leverage(p_outcome, ownership_pct) |
Outcome probability ÷ ownership |
optimize_lineups(pool, n_lineups=1, proj_col="proj", salary_cap=50000, roster_size=6, max_exposure=1.0, min_unique=1, locks=(), excludes=(), min_salary=0) |
Optimal lineups by scipy.optimize.milp |
exposure(lineups) |
Share of lineups containing each golfer |
Example:
dk = dfs.rules("DraftKings")
print("DK hole points:", dk["hole"], "| cap", dk["salary_cap"], "| roster", dk["roster_size"])
m25 = data.event_lookup("Masters", year=2025)["event_id"].iloc[0]
pts = dfs.score_event(m25, dk).sort_values("points", ascending=False)
print(pts[["name", "position", "round_pts", "finish_pts", "points"]].head(3).round(1).to_string(index=False))
DK hole points: {-3: 13.0, -2: 8.0, -1: 3.0, 0: 0.5, 1: -0.5, 2: -1.0, 3: -1.0} | cap 50000 | roster 6
name position round_pts finish_pts points
Rory McIlroy 1.0 98.5 30.0 128.5
Justin Rose 2.0 89.0 20.0 109.0
Patrick Reed 3.0 81.5 18.0 99.5
In the hole table, −3 means double eagle or better and +3 means worse than double bogey.
Limits. DFS sites change their rules; re-check dfs_scoring.md before relying on them. Salaries and ownership in this book are illustrative, never real.
Area 2 — Shots, Strokes Gained and Strategy (SIMULATED)
Everything a golfer "does" in this area is simulated. Label it in your text and on your figures: style.save(fig, path, note="SIMULATED — golfkit.shotsim, seed N").
B.8 golfkit.baselines
Purpose. Expected strokes to hole out, E(lie, distance): the benchmark behind every strokes-gained number. Appendix D prints the tables.
| Call | Returns |
|---|---|
Baseline.pga(green="broadie2011") |
Broadie's PGA TOUR benchmark: tee, fairway, rough, sand, recovery 10–600 yd (Broadie 2012, Table B.1) and green 2–90 ft (Broadie's 2011 putts-gained note). green="esc2014" gives the Every Shot Counts putting column |
Baseline.from_simulation(handicap, n=60000, seed=7, rebuild=False, golfer=None, cache=True) |
A SIMULATED handicap-level baseline, cached in data/processed/baselines/ |
Baseline.from_shots(shots, name="empirical", min_n=30, edges=None) |
An empirical baseline from any shot table, the ShotLink way |
b.expected(lie, distance) |
E(lie, d), vectorised. Yards off the green, feet on it. "holed" → 0 |
b.grid(...), b.compare(other, ...), b.to_frame() |
Wide grid, long comparison, raw table |
bucket_expected(shots, edges=None), strokes_to_hole_out(shots) |
Bucket averages with n and SE; strokes to hole out per shot |
Interpolation is monotone (PCHIP). Off-green lies below 10 yd use the 10-yd value; tee distances below 100 yd use the fairway value; the green curve is anchored at E(0 ft) = 1.
Example:
pga = baselines.Baseline.pga()
sim15 = baselines.Baseline.from_simulation(15.4) # cached SIMULATED 15.4 baseline
print(f"PGA E(fairway,150 yd) = {float(pga.expected('fairway', 150)):.3f} E(green,10 ft) = {float(pga.expected('green', 10)):.3f}")
print(f"SIM15.4 E(fairway,150 yd) = {float(sim15.expected('fairway', 150)):.3f} E(green,10 ft) = {float(sim15.expected('green', 10)):.3f}")
PGA E(fairway,150 yd) = 2.943 E(green,10 ft) = 1.610
SIM15.4 E(fairway,150 yd) = 3.874 E(green,10 ft) = 1.823
Limits.
- The PGA baseline is 2003–2010 ShotLink, excluding the majors. Today's tour putts somewhat better.
- Simulated baselines are built on golfkit's generic holes, so their category zero points differ from those of any real course (Chapter 12, Chapter 15).
- If you change simulator code, bump BASELINE_VERSION so cached baselines are rebuilt.
B.9 golfkit.holes
Purpose. Hole and course geometry for the simulator, targeting and hole maps.
| Call | Returns |
|---|---|
Hole(par=4, length=400.0, fairway_width=32.0, rough_width=15.0, fairway_start=None, dogleg_x=None, dogleg_deg=0.0, green_depth=30.0, green_width=26.0, pin=(0.0, 0.0), left="trees", right="trees", features=[], number=1, stroke_index=1, name="", fringe=1.5, behind=25.0) |
A hole (yards). left/right beyond the rough: "trees", "ob", "water" or "rough" |
Feature(kind, shape, params) |
A hazard or surface: kind sand/water/ob/trees/rough/fairway; shape circle/ellipse/rect/poly |
h.classify(x, y), h.classify_code(x, y) |
Lie names / integer codes (LIE_CODE), vectorised |
h.pin_xy, h.pin_at(along, across), h.green_center, h.edge_distance(x, y), h.copy(**changes) |
Geometry helpers |
Course(name, holes, course_rating=None, slope=None, rating_note="") |
.par, .length, .table(); iterable |
demo_course("tour"), demo_course("member") |
7,200-yd tour course; 6,400-yd member course (CR 70.8 / Slope 125 🧪, assumed values typical of such a tee) |
demo_hole(name) |
water_right_par3, reachable_par5, tight_par4_ob_left, water_right_approach_par4 |
generic_hole(length, rng=None, style="baseline") |
A randomised typical hole (used to build baselines) |
draw_hole(ax, hole, show_pin=True, pin=None, margin=30.0, label=True), draw_shots(ax, shots, ...) |
Overhead maps in house colours |
Example:
h = holes.demo_hole("water_right_approach_par4")
print(f"{h.name}: par {h.par}, {h.length:.0f} yd, pin at ({float(h.pin_xy[0]):.0f}, {float(h.pin_xy[1]):.0f}), right side = {h.right}")
print("lies at three points:", list(h.classify(np.array([250.0, 405.0, 410.0]), np.array([0.0, 0.0, 25.0]))))
member = holes.demo_course("member")
print(f"member course: par {member.par}, {member.length:,.0f} yd, CR {member.course_rating} / Slope {member.slope}")
water_right_approach_par4: par 4, 410 yd, pin at (412, 7), right side = trees
lies at three points: ['fairway', 'green', 'water']
member course: par 72, 6,400 yd, CR 70.8 / Slope 125
The water on this hole is a Feature beside the green, not the hole's right edge, which is trees.
Limits. Holes are flat and windless, balls fly over trees, doglegs are a lateral bend, and the fringe counts as fairway. See also the water-versus-green rule in §B.22.
B.10 golfkit.shotsim
Purpose. The ShotLink-style shot simulator. All output is SIMULATED. Chapter 2 (§2.8) introduces it.
| Call | Returns |
|---|---|
Golfer.tour(name="Tour average") |
A PGA TOUR-average preset calibrated to Broadie's baseline |
Golfer.from_handicap(h, name=None, **overrides) |
A preset smooth in h (valid about −6 to 36; plus handicaps are negative, so "+1.2" is h=-1.2). Any Golfer field can be overridden, and driver_factor scales driver distance |
g.with_(**changes), g.params(), g.dispersion(distance, lie="fairway", tee_shot=False), g.max_distance(lie, par=4), g.carry_table |
Inspection and tweaks; dispersion returns the Gaussian core in yards |
simulate_rounds(golfer, course, n=20, seed=None, random_pins=True, first_round_id=1) |
n rounds → shot DataFrame |
play_round(golfer, course, rng=None, round_id=1, random_pins=True), play_hole(golfer, hole, rng=None, round_id=1, pin=None) |
One round / one hole |
simulate_from(golfer, lie, distance, n=1000, seed=None, hole=None) |
Hole out n balls from (lie, distance); yards, or feet if lie="green" |
round_summary(shots) |
Per round: score, putts, GIR, fairways, scrambling, up-and-down, sand saves, 3-putts, penalties, score types |
putt_make_probability(golfer, distance_ft) |
The putting model's one-putt probability |
rate_course(course, n=400, seed=2026) |
SIMULATED Course Rating, Bogey Rating and Slope |
The shot schema (shared with yardbook): round_id, hole, par, shot_no, club, start_lie, start_dist, start_unit, end_lie, end_dist, end_unit, penalty, holed, start_x, start_y, end_x, end_y, aim_x, aim_y, start_edge_dist. Distances are to the hole (yards off the green, feet on it); end_lie adds water, ob and holed; after water or OB the next row starts from the drop or replay spot; start_edge_dist is yards to the green's edge.
Example:
g = shotsim.Golfer.from_handicap(15.4, name="a 15.4")
shots = shotsim.simulate_rounds(g, member, n=10, seed=1)
print(f"{len(shots)} shot rows; columns start: {list(shots.columns[:8])}")
summ = shotsim.round_summary(shots)
print(summ[["score", "putts", "gir", "fairways", "penalties"]].mean().round(2).to_dict())
905 shot rows; columns start: ['round_id', 'hole', 'par', 'shot_no', 'club', 'start_lie', 'start_dist', 'start_unit']
{'score': 91.8, 'putts': 34.8, 'gir': 5.4, 'fairways': 7.8, 'penalties': 1.3}
(SIMULATED, seed 1, ten rounds on the member course.) The cast of fictional golfers comes ready-made: yardbook.cast.get_cast_member("Rosa") returns her Golfer, and cast_rounds("Rosa") her representative 20-round sample (Appendix I).
Limits.
- Calibrated to published aggregates (Broadie 2008 and 2012, Every Shot Counts, Shot Scope), not to measured golfers. In putting and the short game its amateurs resemble Broadie's 2005–07 Golfmetrics population.
- The tour preset reproduces the 2003–2010 baseline, not today's tour.
- Penalties are water and OB only: no lost balls or unplayables.
- Twenty rounds give category SEs of roughly 0.3–0.7 strokes per round.
- Policy "pin" is the preset default. Three items in §B.22 apply here: water drops, the fairway-wood tee multiplier, and the "optimal" policy.
B.11 golfkit.sg
Purpose. Shot-level strokes gained, the categories, and summaries. For each shot, SG = E(start) − E(end) − 1 − penalty strokes, where E(end) is the value of where the next shot is played from (so drops and replays are included), and 0 if holed. Summed over a hole, SG = E(tee) − score.
| Function | Returns |
|---|---|
strokes_gained(shots, baseline, arg_edge_yd=30.0, arg_fallback_yd=40.0) |
A copy with e_start, e_end, sg, category, subcategory |
categorize(shots, arg_edge_yd=30.0, arg_fallback_yd=40.0) |
"OTT", "APP", "ARG" or "PUTT" per shot |
per_round(sgdf, categories=["OTT", "APP", "ARG", "PUTT"]) |
Round × category, plus T2G and TOTAL |
category_summary(sgdf) |
Mean SG per round by category, with sd, se, rounds |
subcategory_summary(sgdf, category=None) |
By approach band (APP_BANDS: 0, 100, 125 … 225+ yd), putt band (PUTT_BANDS: 0–3 … 40+ ft), ARG lie, OTT club |
broadie2008_categories(sgdf) |
Broadie's 2008 Golfmetrics split (putting, long > 100 yd, short, sand) |
compare_baselines(shots, {label: baseline}) |
The same shots against several baselines |
hole_sg(sgdf) |
SG per hole, with the check SG(hole) = E(tee) − score |
Categories: OTT = tee shots on par 4s and 5s (a re-tee after OB counts); PUTT = shots starting on the green; ARG = other shots starting within 30 yd of the green's edge (this book's, golfkit's, definition; with no edge distance it falls back to 40 yd from the hole 🧪); APP = everything else, including par-3 tee shots.
Example (the ten SIMULATED rounds above, against the PGA TOUR baseline):
s = sg.strokes_gained(shots, pga)
print(sg.category_summary(s).round(2).to_string())
cmp = sg.compare_baselines(shots, {"PGA": pga, "SIM 15.4": sim15})
print(cmp.round(2).to_string())
sg_per_round sd se rounds
category
OTT -3.91 1.00 0.32 10
APP -10.48 2.18 0.69 10
ARG -4.82 1.79 0.57 10
PUTT -3.48 1.14 0.36 10
T2G -19.21 4.02 1.27 10
TOTAL -22.69 3.57 1.13 10
PGA SIM 15.4
category
OTT -3.91 -0.02
APP -10.48 2.02
ARG -4.82 -0.70
PUTT -3.48 0.46
T2G -19.21 1.31
TOTAL -22.69 1.77
The same ten rounds lose 10.48 strokes per round on approach "vs PGA TOUR (Broadie)" and gain 2.02 "vs 15-handicap (SIMULATED baseline)". Part of that gain is a real lesson rather than skill: the simulated baselines are built on generic holes, so their category zero points don't match the member course (Chapter 15).
Limits. Always name the baseline. The ARG boundary is golfkit's stated choice; the PGA TOUR's exact boundary isn't verified in this book's references.
B.12 golfkit.dispersion
Purpose. Shot dispersion as a bivariate normal: fitting, ellipses, plots and sample size. Errors are relative to the aim point: distance (+ long) and lateral (+ right), in yards (feet for putts).
| Call | Returns |
|---|---|
Dispersion(mean_long=0.0, mean_lat=0.0, sd_long=1.0, sd_lat=1.0, rho=0.0, n=0) |
.cov, .mean, .sample(n, rng=None), .summary() |
fit(long, lat), from_shots(shots), from_golfer(golfer, distance, lie="fairway", tee_shot=False) |
A fitted Dispersion |
ellipse(d, k=2.0), ellipse_points(d, k=2.0, n=100) |
Full axis lengths (yd) and angle; outline points |
coverage(k) |
Share inside the k-σ ellipse, 1 − e^(−k²/2) |
sd_standard_error(sd, n), sd_confidence_interval(sd, n, level=0.95), shots_needed(rel_precision=0.1) |
How precisely n shots measure an SD |
plot_dispersion(ax, long, lat, k=(1.0, 2.0), color=None, show_points=True, label=None, feet=False) |
Scatter with ellipses |
Example:
d = dispersion.from_golfer(g, 150)
print({k: round(v, 2) if isinstance(v, float) else v for k, v in d.summary().items()})
print(f"2-sigma ellipse covers {dispersion.coverage(2):.3f}; shots for a 10% SD estimate: {dispersion.shots_needed(0.10)}")
{'n': 0, 'mean_long': -5.02, 'mean_lat': 0.0, 'sd_long': 14.58, 'sd_lat': 14.14, 'rho': 0.0, 'ellipse2_long_axis': 58.33, 'ellipse2_lat_axis': 56.56, 'ellipse2_angle_deg': 0.0}
2-sigma ellipse covers 0.865; shots for a 10% SD estimate: 51
The SIMULATED 15.4-handicapper's 150-yard core pattern is about 14.6 yd deep and 14.1 yd wide (1 SD), centred 5 yd short of the target.
Limits. from_golfer returns the Gaussian core only; real patterns (and the simulator) also have mishits and big misses in the tails. See §B.22 for Golfer.dispersion with lie="tee".
B.13 golfkit.targeting
Purpose. Where to aim, which club, go or lay up, all priced in expected strokes over the golfer's dispersion (Chapters 18–21).
| Call | Returns |
|---|---|
expected_strokes(golfer, hole, aim, start=None, distance=None, lie="fairway", baseline=None, pin=None, method="mc", n=4000, rng=0, tee_shot=None) |
ev, se (MC only), p_green, p_fairway, p_penalty, mean_leave (yd). aim is (x, y) hole yards |
aim_surface(golfer, hole, xs, ys, ..., method="grid", n=400, rng=0, tee_shot=None) |
EV over an aim grid |
optimal_aim(golfer, hole, distance=None, start=None, lie="fairway", baseline=None, pin=None, half_width=None, step=2.0, method="grid", n=400, rng=0, tee_shot=None) |
AimResult: .best, .best_ev, .pin_ev, .center_ev, .gain_vs_pin, .offset_from_pin(), .plot(ax, hole), .to_frame() |
go_or_layup(golfer, hole, distance=None, start=None, lie="fairway", baseline=None, pin=None, leaves=None, method="mc", n=4000, rng=0) |
ev_go, p_success, ev_success, ev_fail, ev_layup, best_leave, break_even_p, decision, the lay-up table |
break_even(ev_success, ev_fail, ev_safe) |
p* = (ev_fail − ev_safe)/(ev_fail − ev_success) |
tee_club_comparison(golfer, hole, baseline=None, clubs=("D", "3W", "HY"), offsets=None, method="mc", n=4000, rng=0) |
Per club: best lateral offset, ev, p_fairway, p_penalty, mean_leave |
default_baseline(golfer) |
The golfer's own baseline if set; Broadie for the tour; else the SIMULATED baseline of round(h) |
Example (Marcus Bell, the book's fictional 7.8-handicapper, on the demo water hole from 160 yd; SIMULATED):
marcus = cast.get_cast_member("Marcus")
res = targeting.optimal_aim(marcus, h, distance=160, method="grid")
print(f"pin EV {res.pin_ev:.3f}, best EV {res.best_ev:.3f}, gain {res.gain_vs_pin:.3f}, offset from pin {tuple(round(v,1) for v in res.offset_from_pin())}")
mc = targeting.expected_strokes(marcus, h, aim=h.pin_xy, distance=160, method="mc", n=20000, rng=0)
print(f"Monte Carlo at the pin: EV {mc['ev']:.3f} (SE {mc['se']:.3f}), P(penalty) {mc['p_penalty']:.3f}")
print(f"break-even p for a risky play: {targeting.break_even(ev_success=3.6, ev_fail=5.2, ev_safe=4.1):.3f}")
pin EV 3.953, best EV 3.636, gain 0.317, offset from pin (-0.8, -12.8)
Monte Carlo at the pin: EV 4.150 (SE 0.007), P(penalty) 0.388
break-even p for a risky play: 0.688
offset_from_pin() is (downrange, lateral) in yards, so the grid says aim about 13 yd left of the pin. But the grid prices the pin aim at 3.953, while the full Monte Carlo shot model prices the same aim at 4.150, because the grid method ignores mishits and big misses. The book's Anchor B numbers for this hole (pin 4.13, optimal 3.74, vs the SIMULATED 7.8 baseline; Chapter 18) come from Monte Carlo. Use method="mc" whenever trouble is severe. The break-even inputs (3.6, 5.2, 4.1) are illustrative: the risky play must succeed 68.8% of the time to beat the safe one.
Limits. The grid method is fast and deterministic but optimistic near hazards. Four known issues are in §B.22: lumpy grids at hazard lines, the island-green drop rule, go_or_layup with an unreachable green, and the missing public pattern-pricing call.
B.14 golfkit.markov
Purpose. A hole as an absorbing Markov chain over (lie, distance-bucket) states, built from shots, for score distributions and scoring-probability maps (Chapter 16).
| Call | Returns |
|---|---|
MarkovHole.from_shots(shots, par=None, name=""), MarkovHole.from_simulation(golfer, hole, n=20000, seed=0, random_pins=True) |
A chain |
m.expected() |
Expected strokes per state |
m.stroke_distribution(start, max_strokes=20), m.score_distribution(start=None, par=None) |
P(k strokes); eagle or better / birdie / par / bogey / double or worse |
m.prob_within(start, m), m.scoring_map(m_by_lie=2) |
P(hole out within m strokes) by state |
m.state(lie, distance) |
The state index for a lie and distance |
check_against_simulation(golfer, hole, n_chain=20000, n_test=20000, seed=0) |
Chain versus direct simulation |
Example (the SIMULATED 15.4 on the water hole):
mh = markov.MarkovHole.from_simulation(g, h, n=5000, seed=3)
print(mh.score_distribution().round(3).to_dict())
{'eagle or better': 0.0, 'birdie': 0.011, 'par': 0.174, 'bogey': 0.382, 'double bogey or worse': 0.433}
Limits. A chain forgets how the ball reached a state (for example, the angle into the green), so it is only as good as its buckets. Check it against direct simulation before relying on it.
B.15 golfkit.whs
Purpose. The World Handicap System, exactly as in data/reference/world_handicap_system.md (Rules of Handicapping, 2024). There is no 0.96 multiplier; it was removed in 2020. Chapter 29 teaches it.
| Function | Returns |
|---|---|
score_differential(ags, course_rating, slope, pcc=0.0) |
(113/Slope) × (AGS − CR − PCC), rounded to a tenth, .5 up |
handicap_index(differentials, low_hi=None, apply_caps=True) |
Index from the most recent 20 (oldest first), with the fewer-than-20 table and the soft and hard caps |
index_history(differentials, dates=None, apply_caps=True, esr=True) |
Index after each score |
differentials_used(n_scores) |
(how many, adjustment) |
course_handicap(index, slope, course_rating, par, rounded=True) |
Index × Slope/113 + (CR − Par) |
playing_handicap(index, slope, course_rating, par, allowance=0.95) |
round(unrounded CH × allowance); ALLOWANCES holds the recommended values |
strokes_received(course_hcp, stroke_index), net_double_bogey(par, strokes_recv), adjusted_gross_score(hole_scores, pars, stroke_index, course_hcp) |
Hole-score caps (par + 5 before an index exists) |
exceptional_score_reduction(differential, index_before) |
−1 or −2 |
round_tenth(x) |
Rounding to a tenth, .5 up |
practice_allocation(sg_by_category, improvement_rates=None, hours=20.0, step=1.0, floor=0.0) |
A practice-hours helper (not part of the WHS) |
Example (the 20 differentials are made up for the illustration):
diff = whs.score_differential(93, 70.8, 125)
print(f"differential for 93 on CR 70.8 / Slope 125: {diff}")
hi = whs.handicap_index([18.2, 16.9, 21.0, 15.4, 19.9, 14.8, 17.7, 20.3, 16.1, 15.9,
22.4, 18.8, 14.2, 17.0, 19.1, 16.6, 15.0, 21.7, 18.0, 16.3])
print(f"index from 20 differentials: {hi}; course handicap at 15.4 on 125/70.8/72: {whs.course_handicap(15.4, 125, 70.8, 72)}")
print(f"net double bogey on a par 4 with 1 stroke: {whs.net_double_bogey(4, 1)}")
differential for 93 on CR 70.8 / Slope 125: 20.1
index from 20 differentials: 15.5; course handicap at 15.4 on 125/70.8/72: 16
net double bogey on a par 4 with 1 stroke: 7
Limits. index_history without dates assumes one score a week when it works out the 365-day Low Handicap Index (🧪). The improvement rates in practice_allocation default to a 🧪 0.03 per hour, which you should replace with your own.
Area 3 — Physics (Model)
B.16 golfkit.flight
Purpose. A 3-D golf-ball flight model: a point mass with drag, Magnus lift and spin decay, coefficients fitted to 70 published TrackMan shots (data/reference/ball_aerodynamics_model.md), plus a 🧪 bounce-and-roll model. Chapter 1 teaches it.
| Call | Returns |
|---|---|
launch(ball_speed_mph, launch_deg, spin_rpm, spin_axis_deg=0.0, direction_deg=0.0, wind=None, air=None, ground=None, land_elev_ft=0.0, dt=0.01, record_path=True, spin_decay=2e-05) |
Trajectory: carry, carry_x, lateral, apex (yd), apex_ft, land_angle, flight_time, land_speed_mph, land_spin_rpm, roll, total, total_lateral, curve, path arrays t, x, y, z (yd), .summary() |
launch_batch(...) |
The same physics vectorised over arrays; returns a dict of arrays |
carry_grid(ball_speed_mph, launch_deg, spin_rpm, metric="carry", **kw) |
Launch × spin grid for heat maps |
optimize_launch(ball_speed_mph, objective="carry", attack_deg=0.0, spin_k=None, smash_a=None, launch_bounds=(4.0, 30.0), spin_bounds=(1000.0, 6000.0), air=None, ground=None) |
Best launch and spin along a real driver delivery at that attack angle, with the dynamic loft and club speed that produce it |
Air(temp_f=59.0, altitude_ft=0.0, rh=0.0, pressure_inhg=None), Air.isa(altitude_ft) |
Atmosphere (.rho, .mu); default ISA sea level, dry |
Wind(speed_mph=0.0, from_deg=0.0, profile=None, ...), Wind.head/tail/from_left/from_right(mph) |
Wind (uniform, or profile="log") |
Ground.normal(), .firm(), .soft(), bounce_roll(...) |
🧪 bounce and roll |
tour_averages(), validate_tour_averages(air=None) |
TrackMan's table; model versus every published row |
Example:
t = flight.launch(171, 10.4, 2545) # TrackMan PGA TOUR driver, 2024 release
print(f"carry {t.carry:.1f} yd, apex {t.apex_ft:.0f} ft, land {t.land_angle:.1f} deg, total {t.total:.1f} yd")
fade = flight.launch(171, 10.4, 2545, spin_axis_deg=5)
print(f"spin axis +5 deg: lateral {fade.lateral:+.1f} yd at landing (+ = right)")
denver = flight.launch(171, 10.4, 2545, air=flight.Air.isa(5280))
print(f"same launch in ISA air at 5,280 ft: carry {denver.carry:.1f} yd")
carry 282.9 yd, apex 102 ft, land 38.1 deg, total 325.2 yd
spin axis +5 deg: lateral +10.9 yd at landing (+ = right)
same launch in ISA air at 5,280 ft: carry 298.2 yd
Limits.
- One ball model, with no ball-to-ball differences and no Reynolds-number term.
- Landing angles run 3–4° shallower than TrackMan's.
- Valid for full shots at about 85–215 mph ball speed with spin parameter S ≥ 0.07; chips are an extrapolation.
- Roll is 🧪, fitted to driver data only: quote carry for irons and wedges.
- The free optimum (attack_deg=None) runs to the low-spin edge of the calibration and is not a target; use the constrained default.
B.17 golfkit.impact
Purpose. Club–ball impact: the D-plane, spin loft, smash factor, start direction, gear effect and strike location. It turns a club delivery into launch conditions (Chapter 3).
| Call | Returns |
|---|---|
club_to_ball(club_speed, club="Driver", dynamic_loft=None, attack=None, face=0.0, path=0.0, strike_offset_mm=0.0, spin_k=None, smash_a=None) |
LaunchConditions: ball_speed_mph, launch_deg, spin_rpm, spin_axis_deg, direction_deg, smash, spin_loft_deg, face_to_path_deg; .fly() flies it |
Delivery(club, club_speed_mph, attack_deg, dynamic_loft_deg, face_deg=0.0, path_deg=0.0, strike_toe_mm=0.0, strike_up_mm=0.0, spin_k=None, smash_a=None, label="") |
A delivery: .to_ball(), .fly(), .with_(...) |
tour_delivery(club, tour="PGA", version="2024 release") |
Reproduces a TrackMan tour-average row exactly (version="legacy (pre-2024)" for the older table) |
amateur_delivery(club="Driver", handicap=None, club_speed=None) |
TrackMan Combine male driver rows by handicap; other clubs scaled 🧪 |
d_plane(dynamic_loft_deg, attack_deg, face_deg=0.0, path_deg=0.0, club="Driver") |
spin_loft_deg, launch_deg, direction_deg, spin_axis_deg |
spin_from_spin_loft(...), smash_from_spin_loft(...), vertical_launch(...), face_share(club), strike_effects(club, toe_mm=0.0, up_mm=0.0, ...) |
Component relations; strike effects are 🧪 |
optimize_delivery(club_speed, attack_deg=0.0, objective="carry", club="Driver", ...) |
Best dynamic loft for a speed and attack angle |
curve_per_degree(club="Driver", ...) |
Yards of curve per degree of face-to-path |
club_params(), tour_rows(), amateur_driver_table(), validate_optimizer(air=None), calibrate_gear_eta(toe_mm=10.0) |
Fitted tables and checks |
Example (Walt Kowalczyk, the book's fictional 18.9-handicapper; his delivery is a 🧪 scenario, Anchor C):
am = impact.amateur_delivery(handicap=18.9) # TrackMan Combine row interpolated at 18.9
walt = impact.Delivery("Driver", 88.0, -5.0, 12.0, smash_a=am.smash_a) # speed, attack, dynamic loft
lc = walt.to_ball()
print(f"Walt (88 mph, attack -5, loft 12): ball {lc.ball_speed_mph:.1f} mph, launch {lc.launch_deg:.1f}, spin {lc.spin_rpm:.0f}, smash {lc.smash:.3f}")
print(f" carry {lc.fly().carry:.1f} yd")
dp = impact.d_plane(dynamic_loft_deg=14, attack_deg=-3, face_deg=2, path_deg=0, club="Driver")
print("D-plane, face 2 open, path 0:", {k: round(v, 2) for k, v in dp.items()})
Walt (88 mph, attack -5, loft 12): ball 125.5 mph, launch 9.5, spin 3247, smash 1.427
carry 178.7 yd
D-plane, face 2 open, path 0: {'spin_loft_deg': 17.12, 'launch_deg': 11.47, 'direction_deg': 1.69, 'spin_axis_deg': 6.6}
Use the Combine row's smash parameter unrounded, as here: rounding it shifts Walt's carry by a tenth of a yard. The D-plane line shows the driver's 85% face share: a face 2° open to a square path starts the ball 1.7° right.
Limits.
- Spin per degree of spin loft differs between populations (the PGA TOUR driver row spins far less than the optimizer and LPGA rows), and the model doesn't explain why.
- Dynamic lofts are inferred, not measured. Strike-location and gear-effect sizes are 🧪 (LOW confidence): the mechanism is right, the magnitudes are calibrated to design intent.
- amateur_delivery uses one attack angle (−1.6°) for every handicap, and its ball speed comes out 1–3 mph high for Combine rows because the smash factor is rounded.
B.18 golfkit.putting
Purpose. A rolling ball on a planar (or two-plane) green: break, capture speed, aim, make probability and expected putts (Chapter 8).
| Call | Returns |
|---|---|
Green(stimp_ft=10.0, slope_pct=0.0, slope_dir_deg=90.0, second_start_ft=None, second_slope_pct=0.0, second_dir_deg=90.0) |
A green. slope_dir_deg is the direction the green falls toward, clockwise from the ball→hole line (90 = falls right) |
aim_line(distance_ft, slope_pct, stimp, slope_dir_deg=90.0, target_past_ft=1.5, green=None), solve_aim(distance_ft, green, target_past_ft=1.5, dt=0.003) |
aim_deg, v0 (m/s), speed_at_hole, aim_offset_ft (+ = right), break_ft, path_ft |
make_probability(distance_ft, slope_pct, stimp, aim_sd_deg, speed_sd_frac, target_past_ft=1.5, slope_dir_deg=90.0, n=2000, rng=None, criterion="simple", green=None) |
Monte Carlo make probability |
simulate_putts(...), roll_many(v0, aim_deg, green, distance_ft, ...) |
Raw Monte Carlo rolls |
expected_putts(...), leave_distribution(...), tour_expected_putts(distance_ft) |
Expected strokes with comeback putts; leave distances; Broadie's tour table |
optimal_target_past(distance_ft, slope_pct, stimp, aim_sd_deg, speed_sd_frac, ..., objective="expected_putts") |
Best pace |
aimpoint_estimate(distance_ft, slope_pct, slope_dir_deg=90.0, ...) |
An AimPoint-style aim, for comparison only (no accuracy claim) |
TOUR_PUTTER |
🧪 {'aim_sd_deg': 1.18, 'speed_sd_frac': 0.077}, calibrated to tour one-putt rates |
capture_speed(offset_m, criterion="simple"), stimp_decel(stimp_ft), speed_for_distance_past(past_ft, stimp_ft), break_table(...) |
Building blocks |
Example:
a = putting.aim_line(10, 2.0, 11) # 10 ft, 2% side slope (falls right), Stimp 11
print(f"10 ft, 2%, Stimp 11: aim {a['aim_offset_ft'] * 12:+.1f} in at the hole, start {a['v0']:.2f} m/s")
p = putting.make_probability(10, 0.0, 11, **putting.TOUR_PUTTER, n=4000, rng=1)
print(f"TOUR_PUTTER make % from 10 ft, flat: {100 * p:.1f}")
print(f"Broadie tour expected putts from 10 ft: {float(putting.tour_expected_putts(10)):.3f}")
print(f"Stimp 10 deceleration: {putting.stimp_decel(10):.3f} m/s^2")
10 ft, 2%, Stimp 11: aim -12.1 in at the hole, start 1.86 m/s
TOUR_PUTTER make % from 10 ft, flat: 38.2
Broadie tour expected putts from 10 ft: 1.610
Stimp 10 deceleration: 0.549 m/s^2
On a green falling right, the aim point is 12.1 inches left of the hole (negative = left).
Limits.
- Pure rolling (no skid) on planar greens; capture uses the simple criterion, with no lip-outs; errors are Gaussian and independent.
- TOUR_PUTTER is calibrated on flat putts only, and it three-putts too often (§B.22). For pace, lag and three-putt questions use yardbook.putting_strategy.LAG_TOUR and LAG_AM90 (Chapter 22).
- The AimPoint-style rule is the book's parameterisation, not AimPoint's own.
B.19 golfkit.weather
Purpose. Air density and its effect on carry (altitude, temperature, humidity), wind tables, and plays-like yardages. It flies fixed launch conditions in different air: the swing doesn't change (Chapter 6).
| Function | Returns |
|---|---|
air_density(temp_f=59.0, altitude_ft=0.0, rh=0.0, pressure_inhg=None), density_ratio(...) |
kg/m³; ratio to 1.225. temp_f=None = ISA temperature for the altitude |
carry_change(club_or_launch, altitude_ft=0.0, temp_f=59.0, rh=0.0, wind=None, base=STANDARD, tour="PGA") |
base_carry, carry, change_yd, change_pct, lateral. Club names are TrackMan's (PGA TOUR 2024 averages; tour="LPGA" available) |
altitude_table(...), pct_per_1000ft(club_or_launch, max_ft=5280.0, ...), yards_per_10f(club_or_launch, ...), titleist_rule(carry_yd, altitude_ft) |
Altitude and temperature effects; the Titleist rule (carry × (1 + ft × 0.00116/100)) |
wind_table(club_or_launch="Driver", speeds_mph=(5, 10, 15, 20), profile=None, tour="PGA") |
head_yd, tail_yd, head_tail_ratio, cross_drift_yd |
plays_like(yards, club="7-iron", temp_f=59.0, altitude_ft=0.0, wind_mph=0.0, wind_from_deg=0.0, elevation_change_ft=0.0, rh=0.0, wind_profile=None, tour="PGA") |
plays_like, adjustment_yd, scale, lateral_yd; raises ValueError when the club's profile can't reach |
shot(club_or_launch, tour="PGA") |
Launch conditions for a club name |
Example:
cc = weather.carry_change("7-iron", altitude_ft=5280, temp_f=None)
print("7-iron at 5,280 ft (ISA temp):", {k: round(v, 1) for k, v in cc.items()})
pl = weather.plays_like(150, "7-iron", wind_mph=10, wind_from_deg=0)
print("150 yd into 10 mph:", {k: round(v, 1) for k, v in pl.items()})
print(f"driver yd per 10 F: {weather.yards_per_10f('Driver'):.2f}; Titleist rule 280 yd at 5,280 ft: {weather.titleist_rule(280, 5280):.1f}")
7-iron at 5,280 ft (ISA temp): {'base_carry': 169.7, 'carry': 184.0, 'change_yd': 14.3, 'change_pct': 8.4, 'lateral': 0.0}
150 yd into 10 mph: {'plays_like': 169.9, 'adjustment_yd': 19.9, 'scale': 1.0, 'lateral_yd': 0.0}
driver yd per 10 F: 2.03; Titleist rule 280 yd at 5,280 ft: 297.1
Always give altitude effects as a percentage with the club: in this model the tour 7-iron gains 8.4% at a mile high, more than the driver.
Limits. Air density only: no cold-ball effect and no swing changes in wind. plays_like assumes the club's launch profile scales with ball speed.
B.20 golfkit.biomech
Purpose. Simple, documented speed-to-distance relationships, and published kinematic-sequence data (Chapter 7).
| Function | Returns |
|---|---|
carry_from_club_speed(club_speed_mph, club="Driver", mode="fixed", attack_deg=0.0, delivery=None, air=None) |
ball_speed_mph, launch_deg, spin_rpm, carry, total. mode="fixed" keeps one delivery; "optimized" re-optimises dynamic loft at each speed |
speed_carry_curve(speeds_mph=range(70, 131, 5), ...), carry_per_mph(speeds_mph=(80, 90, 100, 110, 120), **kw) |
A curve; its least-squares slope (yd per mph) |
kinematic_sequence(study="Hebert-Losier & Wardell 2024"), plot_kinematic_sequence(ax=None, study=...) |
Published peak segment speeds (deg/s) and timings; also Neal et al. 2007 and Myers et al. 2008 |
Example:
c = biomech.carry_from_club_speed(100, mode="optimized", attack_deg=0)
print("100 mph driver, loft optimised, attack 0:", {k: round(v, 1) for k, v in c.items() if isinstance(v, (int, float))})
print(f"carry per mph (75-120 mph, optimised, attack 0): {biomech.carry_per_mph(range(75, 121, 5), mode='optimized'):.2f} yd")
100 mph driver, loft optimised, attack 0: {'club_speed_mph': 100, 'ball_speed_mph': 146.6, 'launch_deg': 11.6, 'spin_rpm': 2987.1, 'carry': 232.7, 'total': 271.2}
carry per mph (75-120 mph, optimised, attack 0): 3.07 yd
Limits. Speed is the input, not the output: the module says what extra speed is worth, not how to get it. The kinematic data are published group means, not a model of any individual swing.
B.21 golfkit.style
Purpose. The house chart style, so every figure in the book reads as one system (Appendix A, §A.7).
| Name | What it is |
|---|---|
use() |
Apply the style (white surface, light grid, no top or right spines, fixed colour cycle). Call once per script |
save(fig, path, note=None) |
Save the PNG (150 dpi, tight box) with an optional source note at the bottom left, then close the figure. The folder must exist |
SERIES |
Eight categorical colours, used in fixed order, never cycled at random |
GAIN, LOSS, NEUTRAL, sg_colors(values) |
The strokes-gained pair: blue for ≥ 0, orange for < 0 |
SEQ_CMAP, DIV_CMAP |
Sequential (one hue) and diverging colour maps |
TEXT, TEXT_2, GRID, SURFACE |
Text and background colours |
FAIRWAY, ROUGH, GREEN, SAND, WATER, OB |
Hole-map feature colours (not data series) |
Example:
fig, ax = plt.subplots(figsize=(7, 3))
for i, club in enumerate(["Driver", "7-iron"]):
s = weather.shot(club)
tr = flight.launch(s["ball_speed_mph"], s["launch_deg"], s["spin_rpm"])
ax.plot(tr.x, tr.z * 3, color=style.SERIES[i], label=club)
ax.set_xlabel("Distance (yd)"); ax.set_ylabel("Height (ft)"); ax.legend()
style.save(fig, IMG / "appb-fig-style-demo.png", note="golfkit model; TrackMan 2024 tour averages")
print("saved", (IMG / "appb-fig-style-demo.png").name, "| sg_colors([1.2, -0.4]) =", style.sg_colors([1.2, -0.4]))
saved appb-fig-style-demo.png | sg_colors([1.2, -0.4]) = ['#257de0', '#f47230']
Rules of use. One y-axis per chart (no twin axes); past about three series in a scatter, facet or fold into "Other"; every figure carries its source note, with "SIMULATED — golfkit.shotsim, seed N" for simulated data, and hypothetical prices or salaries labelled as such.
B.22 Known Limitations
These are known issues in the current toolkit. Each was found while writing a chapter, and none is hidden: the chapters that meet them say so, and most have a workaround in the yardbook project. Several are left unfixed on purpose, because fixing the simulator would shift every seeded number already published in the book. If you build on golfkit, treat this list as part of the documentation.
Putting (golfkit.putting)
- The default tour putter three-putts too often.
TOUR_PUTTERwas calibrated to tour one-putt rates only, and its 7.7% speed error produces too many long leaves, so it overstates three-putts. For any pace, lag or three-putt question, useyardbook.putting_strategy.LAG_TOUR, which is fitted to Broadie's one-putt and three-putt rates, orLAG_AM90for a 90-golfer (Chapter 22). - Aim solutions can fail on steep, long side-hill putts.
aim_lineraises aValueErroron some of them. Worse,solve_aimcan silently return an invalid line on some side-hill putts struck at low pace (for example 15 ft on a 3% slope with a target 0.25 ft past). Check that the solution's path actually reaches the hole, or useyardbook.putting_strategy, which checks and raises an error.yardbook.greens.aim_pointcan also return a bogus aim while reportingok=Truein such cases.
The shot simulator (golfkit.shotsim)
- Water drops can loop. After a ball finds water, the simulator drops at the last dry point on the line back toward the start and keeps the same aim, so a few holes turn into disasters: three or more penalties on roughly 0.2–0.7 holes per 1,000 for the cast. In a 5,000-play stress test of one water hole, a single play produced a 78 with 38 drops. Averages barely move (capping hole scores at 15 changed one hole's mean by 0.018 strokes), but tails, maximums and blow-up counts are affected. Cap hole scores, or report medians alongside means, when the tail matters.
- Fairway woods off the tee get the approach multiplier. For golfers with an approach-dispersion multiplier, such as Rosa Delgado (×1.30), the simulator also applies it to 3-wood and other non-driver tee shots on par 4s and 5s. Her tee 3-wood comes out at a 24.4-yd lateral SD instead of 18.8. Relatedly,
Golfer.dispersion(d, lie="tee")applies the par-3 tee multiplier to any non-driver tee shot.yardbook.tee_strategycorrects both withtee_fix=True(Chapter 21). policy="optimal"can score worse thanpolicy="pin"on some holes. The chapters find aims with a Monte Carlo search instead (Chapters 18 and 39).- Two routes to "expected strokes" differ slightly.
simulate_fromandBaseline.from_simulationdisagree by about 0.1 strokes at 40–50 yd from the fairway. Compare like with like: don't mix the two in one table (Chapter 9).
Holes and targeting (golfkit.holes, golfkit.targeting)
- Water overrides green. Where a water feature overlaps the green,
Hole.classify_codeclasses the spot as water, contrary to its docstring. - The island-green drop rule is too lenient. A ball that flies over an island green can be dropped back on the island, which is cheaper than real golf. The chapters that meet it (18 and 39) say so and search aims by Monte Carlo.
- The grid method is lumpy at hazard lines. Its 7 × 7 quadrature of the dispersion pattern is coarse, so
optimal_aim(method="grid")can pick an "optimum" that loses to the centre of the green when re-checked withmethod="mc".yardbook.aim.optimal_aimprices aims over a much finer landing grid (40 nodes per axis), and the chapters re-check winners by Monte Carlo (Chapter 18). go_or_layupdoesn't check reach. It prices "go" even when the green is out of range, and it can offer lay-ups longer than the golfer's longest club.yardbook.decisions.go_or_layupguards both (Chapter 20).- No public pattern-pricing call. golfkit has no public function that prices an arbitrary landing pattern on a hole. Chapter 23's fitting code reaches into two private helpers (
targeting._costandtargeting._resolve), which may change without notice. For your own work, useyardbook.aim.expected_strokes_at(Chapter 23).
Impact (golfkit.impact)
- The tour pitching-wedge launch is a touch high.
impact.tour_delivery("PW")launches at 23.97° against TrackMan's published 23.7°. It is small, but visible if you print both.
Betting (golfkit.betting)
overroundis absolute, not relative, for top-N markets. It returns Σ 1/d − target. For a win market (target 1) that is the familiar margin, but for a top-10 market (target 10) a 20% margin shows as 2.00.04_known_limits.py:
fair = np.full(50, 10 / 50) # HYPOTHETICAL top-10 market: 50 runners, p = 0.2 each
odds = 1 / (fair * 1.20) # every price shaded by a 20% margin
print(f"sum of implied probabilities: {np.sum(1 / odds):.2f} (fair total 10)")
print(f"betting.overround(odds, target=10) = {betting.overround(odds, target=10):.2f} (absolute excess)")
print(f"relative margin = {betting.overround(odds, target=10) / 10:.2f}")
print(f"yardbook.bets.market_overround(odds, target=10) = {bets.market_overround(odds, target=10):.2f} (relative)")
sum of implied probabilities: 12.00 (fair total 10)
betting.overround(odds, target=10) = 2.00 (absolute excess)
relative margin = 0.20
yardbook.bets.market_overround(odds, target=10) = 0.20 (relative)
Divide by the target, or use yardbook.bets.market_overround, before comparing margins across markets (Chapter 36).
Data gaps you will meet
- Missing yardages. 35 of the 1,061 events have no ESPN course document, so
hole_scoringhas no yardage for 360 of its 21,006 event-holes (2004–2026). Yardage-based analyses must drop or fill those holes and say which. Chapter 39 fills 320 event-holes from the nearest year's scorecard for the same course, and flags them. (Appendix C, §C.3, has the counts.)
B.23 Tests, Caches and Versions
- Tests.
python -m pytest toolkit/tests -qruns 128 tests covering all three areas and the cast (128 passed on the machine used for this book). Area 1's tests use synthetic fixtures plus real-data smoke tests; Area 3's check the model against the published TrackMan rows. - Caches.
data/processed/cache/holds the SG table (sg_<key>.parquet), walk-forward predictions (wf_<key>.parquet) and hole-SG-by-par tables.data/processed/baselines/holds the simulated baselines. Keys hash the module version, the parameters and the source files' timestamps, so a rebuilt dataset invalidates them automatically. Delete a cache folder to force a rebuild. - Version strings.
sgtotal.SG_VERSION,predict.PREDICT_VERSIONandbaselines.BASELINE_VERSIONare part of the cache keys. If you change the code behind one of them, bump it. - Exploring further.
help(module.function)prints a docstring;appendices/_code/appendix_b/00_dump_signatures.py data sgtotalprints every public name and signature of the modules you list.