Appendix I — The yardbook Guide

yardbook is the Python package you build alongside the book. Each chapter adds one module, and Chapter 40 wires them into a single report: one command turns a file of your shots into an HTML page with strokes gained against four yardsticks, your dispersion, an aim calculator, an equipment summary, a practice plan, a progress test and a handicap trend. The chapters explain why each piece works; this appendix says how to call it. Appendix B documents golfkit, the toolkit underneath.

How this guide was checked. Every signature was read from the code with inspect.signature by 00_dump_signatures.py, which prints the full API of all 42 modules. Only the main functions are listed, with long defaults shortened to .... Every example is an excerpt of a script in appendices/_code/appendix_i/, and every output block is pasted from running it (saved as NN_output.txt).


I.1 Install and run

You need Python 3.11 or newer (the book was run with 3.13) and the packages in the book's requirements.txt. From the book's root folder:

python -m venv .venv
# Windows: .venv\Scripts\activate      macOS/Linux: source .venv/bin/activate
python -m pip install -r requirements.txt

yardbook lives in project/yardbook/ and isn't installed with pip. Either run from project/ (python -m yardbook ... then just works, and yardbook finds golfkit in toolkit/ by itself), set PYTHONPATH to project, or use the book's standard header in your own scripts:

import sys; from pathlib import Path
BOOK = Path(__file__).resolve().parents[3]          # adjust the depth to where your script lives
sys.path.insert(0, str(BOOK / "toolkit")); sys.path.insert(0, str(BOOK / "project"))

A quick check (01_cli_and_schema.py, part 1):

import yardbook
print(f"yardbook {yardbook.__version__}: {len(yardbook.__all__)} modules")
yardbook 0.1.0: 42 modules

What needs downloaded data. The personal modules, including the dashboard, need no download. The tour modules (legacy_stats, tour_data, ratings, course_fit, forecast, majors, dfs, course_profile, and the REAL options in scoring_odds and tee_strategy) read the ESPN tables in data/processed/, built once with the three commands in the book's README (Appendix C).


I.2 The command line

python -m yardbook has two sub-commands: cast-csv writes a SIMULATED cast member's rounds as a shot file, so you can try the report first, and report builds the page.

$ python -m yardbook cast-csv rosa --out <tmp>\rosa.csv
wrote <tmp>\rosa.csv: 20 SIMULATED rounds for Rosa Delgado (seed 154023, nominal index 15.4)
[exit 0, 1 s]
$ python -m yardbook report --shots <tmp>\rosa.csv --handicap 15.4 --name Rosa --out <tmp>\rosa.html --note SIMULATED - yardbook.cast Rosa Delgado, seed 154023
wrote <tmp>\rosa.html (20 rounds, 12 s)
  1. Practise: put 20 of your next 20 practice hours into approach
  2. Play: on approaches with trouble on one side, aim about 9 yd left of the flag, away from the trouble
  3. Prove: log every round; judge the plan after about 126 rounds, not 5
[exit 0, 14 s]
rosa.html: 921 KB

(SIMULATED; <tmp> is the script's temporary folder.) The three printed lines are the report's "three things to do next". The page is self-contained, with every chart embedded. cast-csv takes rosa, marcus, walt, emma, tasha or dev, plus optional --rounds (default 20) and --seed (default: the member's representative seed).

report options.

Option Meaning Default
--shots PATH your shot CSV (schema in I.3) required
--handicap H your Handicap Index; plus handicaps are negative (+1.2 is -1.2) required
--out PATH the HTML page to write report.html
--name NAME the name on the report You
--target T the level the practice plan aims at round(H − 3)
--course-rating CR, --slope S your tees' rating, for the handicap section member course's 🧪 70.8 / 125 if your pars match it, else 🧪 72.0 / 113
--change-after ID the last round_id before a change you want to test none (a first-half v second-half noise check)
--hours N practice hours to plan 20
--driver-speed MPH, --attack DEG, --dynamic-loft DEG turn on the driver model scenario off; attack 0, loft 12
--aim-distance YD distance for the aim calculator 160
--note TEXT a footnote printed on every chart none
--no-peers skip the same-course peers column peers on for the member course
--images-beside save PNGs next to the page instead of embedding them embedded
--quick fewer bootstrap resamples: faster, noisier intervals off

Exit codes. 0 on success; 2 for a missing file or a shot file with validation errors, with the problems listed (I.6 shows one).


I.3 The data schema

Every personal module reads one table, one row per stroke, in Chapter 2's layout. The simulator and cast produce exactly this layout, so anything you run on the cast runs on your own file.

Column Meaning
round_id your round number; number rounds oldest first (the progress test reads them in order)
hole, par hole number and par
shot_no 1, 2, … within the hole
club D 3W 5W 7W HY 2i … 9i PW GW SW LW P (unknown names are a warning)
start_lie, end_lie tee fairway rough sand recovery green; an end lie can also be water, ob or holed
start_dist, end_dist distance to the hole: yards off the green, feet on it
start_unit, end_unit yards or feet, matching the lie
penalty penalty strokes incurred by this shot
holed True only on the last shot of the hole

Optional columns unlock more (rounds.OPTIONAL_SHOT_COLUMNS lists the six coordinates; the loaders keep any other column you add):

Optional column Meaning What needs it
start_x, start_y where the ball was, in hole coordinates (yards; tee at the origin, x downrange, y + right) dispersion fits (Ch 19); the dashboard's club-pattern and aim sections
end_x, end_y where it finished, same coordinates the same; end_y also gives a missed fairway's side
aim_x, aim_y where you aimed, same coordinates the same: the dashboard's club-pattern and aim sections, and the aim tip in its "Play" box, need all six coordinates
start_edge_dist yards to the green's edge the exact 30-yard around-the-green rule; without it golfkit uses a 🧪 40-yards-from-the-hole proxy

None is required: without the coordinates, those sections say they were skipped and everything else is unchanged (Chapter 40's C8 checks this). The cast files carry all seven. A separate scorecard layout holds hole totals. rounds.write_templates(folder) writes a template of each:

--- shots_template.csv
round_id,hole,par,shot_no,club,start_lie,start_dist,start_unit,end_lie,end_dist,end_unit,penalty,holed
1,1,4,1,D,tee,385,yards,fairway,148,yards,0,False
1,1,4,2,8i,fairway,148,yards,green,22,feet,0,False
1,1,4,3,P,green,22,feet,green,2,feet,0,False
1,1,4,4,P,green,2,feet,holed,0,feet,0,True
--- scorecard_template.csv
round_id,date,course,tees,course_rating,slope,hole,par,yards,strokes,putts,fairway,gir,penalties
1,2026-05-02,My Club,White,70.1,124,1,4,385,4,2,hit,True,0
1,2026-05-02,My Club,White,70.1,124,2,3,162,4,2,,False,0
scorecard: 2 rows checked — 1 errors, 0 warnings
  error   hole_count                   1

Delete the example rows before typing your own; the scorecard template fails hole_count because it shows two holes, not 9 or 18. Each shot starts where the last one finished (148 yards, fairway), and validate_shots checks that chain.


I.4 Module by module

One section per module, in chapter order: its job, main functions, an example and the chapter that builds it. The examples share this setup:

from golfkit.baselines import Baseline
from golfkit import holes, impact, shotsim
from yardbook import cast
rosa = cast.cast_rounds("rosa")                      # 20 SIMULATED rounds, seed 154023
marcus = cast.get_cast_member("marcus")              # a SIMULATED Golfer
pga, sim12 = Baseline.pga(), Baseline.from_simulation(12)
hole = holes.demo_hole("water_right_approach_par4")  # 410-yd par 4, water right of the green

Sections I.4.0–I.4.14 are in 02_modules_ch01_14.py, I.4.15–I.4.29 in 03_modules_ch15_29.py and I.4.30–I.4.40 in 04_modules_ch30_40.py. All run in under a minute.

I.4.0 cast (provided with the book)

The six fictional golfers as SIMULATED Golfer objects, each a handicap preset plus a documented quirk (the "truth" Chapter 40 tries to recover; it's in the module's docstring).

get_cast_member(name) -> Golfer
cast_rounds(name, n=20, seed=None, course=None, random_pins=True) -> DataFrame
scorecard(shots, course=None, handicap_index=None, pcc=0.0) -> DataFrame
print(cast.cast_names())
card = cast.scorecard(rosa)              # wide: holes 1-18, out, in, total, putts, ...
print(len(rosa), "shots,", rosa["round_id"].nunique(), "rounds; mean score", round(card["total"].mean(), 2))
['Rosa Delgado', 'Marcus Bell', 'Walt Kowalczyk', 'Emma Sato', 'Tasha Nguyen', 'Dev Raman']
1835 shots, 20 rounds; mean score 93.4

Names match loosely ("rosa" works). Each default seed was chosen as the most representative of 60 candidates; pass other seeds to see the noise.

I.4.1 ball_flight — Chapter 1

Launch conditions in, ball flight out, through golfkit's validated flight model.

LaunchData(ball_speed_mph, launch_deg, spin_rpm, spin_axis_deg=0.0, direction_deg=0.0, label='', club=None)
flight_table(launches, **kwargs) -> DataFrame
from yardbook.ball_flight import LaunchData, flight_table
ld = LaunchData(ball_speed_mph=171, launch_deg=10.4, spin_rpm=2545, label="PGA TOUR avg driver")
print(flight_table([ld])[["label", "carry", "total", "apex_ft", "land_angle"]].round(1).to_string(index=False))
              label  carry  total  apex_ft  land_angle
PGA TOUR avg driver  282.9  325.2    101.8        38.1

The inputs are TrackMan's published PGA TOUR driver averages (2024 release); the MODEL carry, 282.9 yards, sits beside TrackMan's published 282.

I.4.2 rounds — Chapter 2

The data model: schema constants, loaders, validation and scorecards.

validate_shots(shots, max_shots_per_hole=15, strict_clubs=False, chain_tol=None) -> ValidationReport
load_shots_csv(path, column_map=None, validate=True, raise_on_error=False) -> DataFrame
scorecard_from_shots(shots, course=None) -> DataFrame;  write_templates(directory) -> dict
from yardbook import rounds
paths = rounds.write_templates(tmp)                  # tmp: any folder
shots = rounds.load_shots_csv(paths["shots"])
print(rounds.validate_shots(shots).summary())
print(rounds.scorecard_from_shots(shots)[["round_id", "hole", "par", "strokes", "putts"]].to_string(index=False))
shots: 4 rows checked — 0 errors, 0 warnings (clean)
 round_id  hole  par  strokes  putts
        1     1    4        4      2

Errors (such as bad_lie, chain_break, not_holed_out, penalty_missing) make a file unusable; warnings (too_many_shots, unknown_club, distance_increase) are worth a look.

I.4.3 strike — Chapter 3

Read a launch-monitor session the way a fitter does: spin loft, smash ceiling, face and path.

spin_loft(dynamic_loft_deg, attack_deg);  smash_ceiling(cor=0.83, head_g=200.0, ball_g=45.93) -> float
expected_smash(spin_loft_deg, club='Driver', smash_a=None)
from yardbook import strike
print(f"spin loft {strike.spin_loft(12.0, -5.0):.1f} deg; smash ceiling {strike.smash_ceiling():.3f}; "
      f"expected smash at that spin loft {strike.expected_smash(17.0):.3f}")
spin loft 17.0 deg; smash ceiling 1.488; expected smash at that spin loft 1.444

I.4.4 distances — Chapter 4

Your personal distance matrix from a range session, plus a driver launch check.

simulate_range_session(bag, n_per_club=30, noise='mid', seed=0, air=None, ground=None) -> DataFrame
distance_matrix(shots, club_col='club', carry_col='carry', total_col='total', lateral_col='lateral', order=None) -> DataFrame
from yardbook import distances
sess = distances.simulate_range_session(distances.amateur_bag(88.0), n_per_club=10, seed=4)
print(distances.distance_matrix(sess)[["club", "n", "carry_median", "carry_sd"]].head(4).round(1).to_string(index=False))
  club  n  carry_median  carry_sd
Driver 10         177.6       5.9
3-wood 10         154.5      13.0
5-wood 10         150.5      15.4
Hybrid 10         139.6      12.8

(SIMULATED, seed 4.) distance_matrix also reads your own launch-monitor CSV.

I.4.5 shape — Chapter 5

The modern ball-flight laws, the nine-shot grid and miss diagnosis.

ball_flight_laws(face, path, club='7-iron', delivery=None, hand='R', **fly_kw) -> dict
diagnose_miss(start_deg=None, curve_yd=None, *, face=None, path=None, club='7-iron', ...) -> dict
from yardbook import shape
d = shape.diagnose_miss(face=2.0, path=-2.0, club="7-iron")
print(d["shape"], {k: round(d[k], 1) for k in ("start_deg", "face_to_path", "curve_yd", "carry")})
fade {'start_deg': 0.9, 'face_to_path': 4.0, 'curve_yd': 14.7, 'carry': 168.8}

A nearly straight start and 14.7 yards of curve: a face-to-path problem. Physics modules use TrackMan club names ("7-iron"), not the simulator's ("7i").

I.4.6 conditions — Chapter 6

Adjust a yardage for temperature, altitude, wind, humidity and elevation change.

plays_like(yards, temp_f=59.0, altitude_ft=0.0, wind_mph=0.0, wind_dir_deg=0.0, club=None, *, ...) -> dict
club_for(yards, ...) -> str;  conditions_carry(bag=None, ...) -> DataFrame
from yardbook import conditions
r = conditions.plays_like(150, temp_f=45, wind_mph=10, wind_dir_deg=0)   # 0 = headwind
print({k: (round(r[k], 1) if isinstance(r[k], float) else r[k]) for k in ("plays_like", "club_short", "club_long", "adjustment_yd")})
{'plays_like': 172.9, 'club_short': '7-iron', 'club_long': '6-iron', 'adjustment_yd': 22.9}

(MODEL, default tour bag; pass bag= for yours.)

I.4.7 speed — Chapter 7

What club speed is worth, and whether a speed-training log shows real progress.

carry_from_speed(club_speed, attack_deg=0.0, mode='optimized', dynamic_loft_deg=None, ...) -> dict
speed_or_delivery(club_speed, attack_deg, dynamic_loft_deg, extra_mph=(1, 3, 5), new_attacks=(0.0, 3.0), ...) -> DataFrame
from yardbook import speed
t = speed.speed_or_delivery(88.0, -5.0, 12.0)        # Walt's delivery; golfkit's default smash
print(t[["option", "lever", "carry", "gain_yd"]].round(1).to_string(index=False))
                      option     lever  carry  gain_yd
            current delivery      none  182.2      0.0
       +5 mph, same delivery     speed  199.4     17.2
best loft, same attack angle equipment  184.9      2.7
       attack +0°, best loft  delivery  195.4     13.2
       +5 mph and attack +0°      both  211.1     28.9

(MODEL; five of eight rows.) driver.driver_payoff (I.4.24) uses the smash for Walt's handicap instead of golfkit's default, so its "today" carry is 178.7.

I.4.8 greens — Chapter 8

Putting physics on a planar green: aim points, break charts and make curves.

aim_point(distance_ft, slope_pct, stimp, slope_dir_deg=90.0, target_past_ft=1.5) -> dict
break_chart(distances_ft, slopes_pct, stimp, ...) -> DataFrame;  effective_stimp(stimp, grade_pct, uphill=True) -> float
from yardbook import greens
a = greens.aim_point(10, 2.0, 11.0)                  # 10 ft, 2% side slope, Stimp 11
print(f"aim {a['aim_in']:.1f} in ({a['aim_cups']:.2f} cups) {a['aim_side']}; AimPoint rule of thumb {a['aimpoint_rule_in']:.1f} in")
aim 12.1 in (2.85 cups) left; AimPoint rule of thumb 9.3 in

I.4.9 wedges — Chapter 9

Your wedge matrix (clubs × clock-face swings) and a scoring-zone report.

wedge_delivery(loft_deg, driver_speed_mph=115.0, swing='full', label='') -> Delivery;  fly_wedge(delivery, air=None) -> dict
scoring_zone_report(shots, baseline, bands=None, lies=None) -> DataFrame;  up_and_down(shots, max_yd=50.0) -> dict
from yardbook import wedges
for sw in ("9:00", "full"):
    f = wedges.fly_wedge(wedges.wedge_delivery(54, driver_speed_mph=104.6, swing=sw))
    print(f"SW 54 deg, {sw}: carry {f['carry']:.1f} yd, launch {f['launch_deg']:.1f} deg, spin {f['spin_rpm']:.0f} rpm")
SW 54 deg, 9:00: carry 60.8 yd, launch 28.2 deg, spin 6345 rpm
SW 54 deg, full: carry 103.8 yd, launch 28.2 deg, spin 9064 rpm

(MODEL; Coach Tasha's 104.6 mph driver speed and 54° sand wedge.)

I.4.10 sg_core — Chapter 10

Shot-level strokes gained from first principles: $SG = E(\text{start}) - E(\text{end}) - 1 - \text{penalty}$.

price_shot(baseline, start_lie, start_dist, end_lie, end_dist=0.0, penalty=0) -> float
shot_sg(shots, baseline) -> DataFrame;  hole_sg(shots, baseline);  round_sg(shots, baseline)
from yardbook import sg_core
print(f"150 yd fairway -> 20 ft on the green: {sg_core.price_shot(pga, 'fairway', 150, 'green', 20):+.3f} strokes")
print(sg_core.round_sg(rosa, pga).head(3).round(2).to_string(index=False))
150 yd fairway -> 20 ft on the green: +0.073 strokes
 holes  score  par  expected_score  sg_total  sg_check
    18    101   72           69.06    -31.94    -31.94
    18    102   72           69.12    -32.88    -32.88
    18     95   72           69.09    -25.91    -25.91

sg_check confirms the telescoping identity in every row.

I.4.11 sg_report — Chapter 11

Strokes gained by category (OTT, APP, ARG, PUTT) per round, with round-bootstrap intervals.

category_report(shots, baseline, arg_edge_yd=30.0, n_boot=4000, seed=7) -> DataFrame
compare_report(shots, baselines, ...) -> dict;  biggest_leak(report) -> dict;  leak_summary(report) -> str
from yardbook import sg_report
rep = sg_report.category_report(rosa, sim12)
print(sg_report.leak_summary(rep))
Strokes gained per round vs SIMULATED 12.0 handicap baseline (20 rounds):
  Off-the-Tee       -0.59  (95% CI -1.24 to +0.03; 14.4 shots/rd)
  Approach          -3.29  (95% CI -5.30 to -1.35; 27.4 shots/rd)
  ...
  Total             -3.84  (95% CI -6.26 to -1.26; 91.8 shots/rd)
  Biggest leak: Approach -3.29 (CI excludes 0)

Rosa's headline numbers against a 12 (SIMULATED; trimmed).

I.4.12 baseline — Chapter 12

Build, smooth and compare strokes-gained baselines, and see how the choice changes the answer.

fit_baseline(shots, name='empirical', min_n=30, monotone_lies=(...), edges=None) -> Baseline
sg_under_baselines(shots, baselines) -> DataFrame
from yardbook import baseline as ybl
tab = ybl.sg_under_baselines(rosa, {"PGA TOUR": pga, "SIM 15.4": Baseline.from_simulation(15.4), "SIM 12": sim12})
print(tab.round(2).to_string())
          PGA TOUR  SIM 15.4  SIM 12
category                            
OTT          -3.80      0.36   -0.59
APP         -13.40     -1.55   -3.29
ARG          -4.00      0.48   -0.24
PUTT         -3.11      0.93    0.28
T2G         -21.21     -0.71   -4.12
TOTAL       -24.32      0.21   -3.84

Same shots, three yardsticks, three stories (SIMULATED).

I.4.13 sg_deep — Chapter 13

Sub-categories (distance and lie bands) with bootstrap intervals and Holm-adjusted flags.

subcategory_table(shots, baseline=None, bands=None, app_by='distance') -> DataFrame
bootstrap_ci(shots, baseline=None, bands=None, n_boot=2000, level=0.95, seed=0, ...) -> DataFrame
flag_weaknesses(ci, alpha=0.05, method='holm', min_shots_per_round=0.5) -> DataFrame
from yardbook import sg_deep
fl = sg_deep.flag_weaknesses(sg_deep.bootstrap_ci(rosa, sim12, n_boot=2000, seed=0), method="holm")
sub = fl[fl["level"] == "sub"].sort_values("p")
print(sub[["est", "lo", "hi", "shots_per_round", "p", "p_adj", "weakness"]].head(3).round(3).to_string())
                  est     lo     hi  shots_per_round      p  p_adj  weakness
sub                                                                         
APP 225+ yd    -1.000 -1.653 -0.424              5.0  0.000  0.009      True
APP 100–125 yd -0.752 -1.412 -0.209              3.6  0.003  0.051     False
APP 125–150 yd -0.574 -1.062 -0.138              3.8  0.013  0.208     False

One band survives the adjustment over 18 tests (Chapter 40, §40.3).

I.4.14 signal — Chapter 14

Separate signal from noise: intervals, power, rounds needed, shrinkage and false-discovery control.

rounds_needed(effect, sd, power=0.8, alpha=0.05, sided=2) -> int;  power(effect, sd, n, alpha=0.05, sided=1) -> float
is_improvement_real(before, after, lower_is_better=True, alpha=0.05, n_boot=4000, seed=0) -> dict
from yardbook import signal
print("rounds per period, 1 stroke at sd 2.756:", signal.rounds_needed(1.0, 2.756))
print("power, 1.54 strokes at sd 4.75, 20 rounds each, one-sided:", round(signal.power(1.54, 4.75, 20), 3))
rounds per period, 1 stroke at sd 2.756: 120
power, 1.54 strokes at sd 4.75, 20 rounds each, one-sided: 0.268

rounds_needed defaults to two-sided and power to one-sided; say which you used.

I.4.15 importers — Chapter 15

Get your golf in from a generic CSV, and approximate strokes gained from a scorecard with yardages.

from_generic_csv(source, template='start_only', column_map=None, imputed_putt_ft=3.0, validate=True, ...) -> DataFrame
to_generic_csv(shots, path=None, template='start_only', course=None, include_edge=False) -> DataFrame
describe_templates() -> DataFrame;  scorecard_approx_sg(card, baseline, handicap=15.0, ...) -> DataFrame
from yardbook import importers
gen = importers.to_generic_csv(rosa[rosa["round_id"] == 1])   # one round in the generic layout
print(list(gen.columns))
back = importers.from_generic_csv(gen)                         # back to the shot schema, validated
print(len(gen), "generic rows ->", len(back), "shots;", back.attrs["validation"].summary())
['round_id', 'date', 'course', 'hole', 'par', 'hole_yards', 'shot_no', 'club', 'lie', 'distance', 'penalty_strokes', 'result']
97 generic rows -> 97 shots; shots: 97 rows checked — 0 errors, 0 warnings (clean)

I.4.16 scoring_odds — Chapter 16

Score distributions from any position, scoring-probability maps and match-play odds.

score_distribution(state, golfer, hole=None, strokes_taken=0, par=None, chain=None, n=20000, seed=0) -> Series
match_play_odds(pmf_a, pmf_b) -> Series;  real_score_table(by='par', ...) -> DataFrame   # REAL
from yardbook import scoring_odds
print(scoring_odds.score_distribution(("fairway", 160), marcus, hole, strokes_taken=1, n=20000, seed=16).round(3).to_string())
mean                     4.881
sd                       1.158
eagle or better          0.000
birdie                   0.036
par                      0.398
bogey                    0.334
double bogey or worse    0.232

(SIMULATED, seed 16: Marcus, 160 yards in the fairway after his drive on the water-right par 4.)

I.4.17 legacy_stats — Chapter 17

Traditional statistics tested against strokes gained on REAL tour data.

load_stats_frame(min_rows=30, single_course=True, sg=None) -> DataFrame;  season_frame(df, min_events=10, min_rounds=30) -> DataFrame
traditional_vs_sg(stats_df, models=None) -> dict;  distance_vs_accuracy(stats_df) -> dict
from yardbook import legacy_stats
S = legacy_stats.season_frame(legacy_stats.load_stats_frame())   # player-seasons
dva = legacy_stats.distance_vs_accuracy(S)
print(f"{dva['n']:,} player-seasons: {dva['per_yard']:+.4f} SG/round per yard of distance, "
      f"{dva['per_pp']:+.4f} per fairway-% point; 1 point = {dva['yards_per_pp']:.2f} yd")
2,106 player-seasons: +0.0390 SG/round per yard of distance, +0.0721 per fairway-% point; 1 point = 1.85 yd

(REAL, ESPN player statistics.) round_stat_line gives the same line for your own shot file.

I.4.18 aim — Chapter 18

Where to aim: expected strokes over your dispersion pattern, searched on a grid of aim points.

optimal_aim(hole, pattern, baseline, start=None, distance=None, pin=None, start_lie='fairway', half_width=None, step=2.0, nodes=40) -> AimPlan
from yardbook import aim, dispersion
pat = dispersion.pattern_from_golfer(marcus, 160)            # Marcus's TRUE 160-yd pattern
plan = aim.optimal_aim(hole, pat.disp, Baseline.from_simulation(7.8), distance=160)
dx, dy = plan.best[0] - plan.pin[0], plan.best[1] - plan.pin[1]   # + long / + right of the flag
print(f"best aim {abs(dy):.0f} yd {'left' if dy < 0 else 'right'}, {dx:+.0f} yd long of the flag: EV {plan.best_ev:.3f}; "
      f"at the flag {plan.pin_ev:.3f}; green centre {plan.center_ev:.3f}")
best aim 13 yd left, +1 yd long of the flag: EV 3.676; at the flag 4.104; green centre 3.791

(SIMULATED.) This prices Marcus's true pattern; the dashboard fits his 38 sampled approaches instead and finds 12 yards left, 0.21 saved (Chapter 40, §40.4).

I.4.19 dispersion — Chapter 19

Your scatter pattern: fit it (plain or robust), plot it, size the sample, use it.

points_from_shots(shots, clubs=None, start_lie=None, dist_range=None) -> DataFrame   # needs aim_x, aim_y
fit_pattern(points, robust=False, cutoff=0.99, max_iter=20) -> Pattern
shots_to_detect_bias(bias, sd, power=0.8, alpha=0.05) -> int
pattern_from_golfer(golfer, distance, lie='fairway', tee_shot=False) -> Pattern
sm = dispersion.pattern_from_golfer(marcus, 160).summary()
print({k: round(sm[k], 1) for k in ("mean_long", "mean_lat", "sd_long", "sd_lat")})
print("shots to detect a 6-yd bias at lateral SD 20.8:", dispersion.shots_to_detect_bias(6.0, 20.8))
{'mean_long': -3.5, 'mean_lat': 4.2, 'sd_long': 13.1, 'sd_lat': 12.3}
shots to detect a 6-yd bias at lateral SD 20.8: 95

(SIMULATED.) Marcus's true 160-yard pattern centres 4.2 yards right.

I.4.20 decisions — Chapter 20

Risk-reward decisions priced in expected strokes: go or lay up, break-even odds, match play.

go_or_layup(golfer, hole, distance, lie='fairway', baseline=None, leaves=None, n=4000, rng=0) -> dict
break_even(ev_success, ev_fail, ev_safe) -> float;  read_break_even(p_star, p=None) -> str
from yardbook import decisions
g5 = shotsim.Golfer.from_handicap(5)                          # a SIMULATED 5-handicap preset
o = decisions.go_or_layup(g5, holes.demo_hole("reachable_par5"), 215, n=4000, rng=20)
print({k: (round(o[k], 3) if isinstance(o[k], float) else o[k])
       for k in ("max_distance", "ev_go", "ev_layup", "p_success", "break_even_p", "decision")})
{'max_distance': 239.7, 'ev_go': 3.879, 'ev_layup': 4.114, 'p_success': 0.253, 'break_even_p': 0.042, 'decision': 'go'}

(SIMULATED, rng 20.) Going saves 0.235 strokes though only a quarter of go shots find the green.

I.4.21 tee_strategy — Chapter 21

Which club off the tee, and where to aim it, for your pattern on a given hole.

club_off_tee(hole, golfer, clubs=('D', '3W', 'HY'), offsets=None, baseline=None, n=4000, rng=0, habit=('D', 0.0), tee_fix=True) -> TeePlan
fairway_equivalent_yards(baseline, distance, lie='rough', max_yards=300.0) -> float
from yardbook import tee_strategy
print(f"150 yd from the rough plays like {tee_strategy.fairway_equivalent_yards(pga, 150):.0f} yd from the fairway (PGA TOUR baseline)")
150 yd from the rough plays like 50 yd from the fairway (PGA TOUR baseline)

That is 50 yards farther back: rough at 150 equals fairway at about 200. tee_fix=True corrects a simulator quirk (I.8).

I.4.22 putting_strategy — Chapter 22

Pace, lag and safe-side decisions on the green, with putters fitted to Broadie's one- and three-putt rates.

LAG_TOUR, LAG_AM90                                  # the book's fitted putters
hole_out(distance_ft, putter, stimp=11.0, pace_ft=None, n=20000, seed=0, ...) -> dict
make_zone_radius(putter, stimp=11.0, target=0.95) -> float;  safe_side(distance_ft, slope_pct, putter, ...) -> DataFrame
from yardbook import putting_strategy as ps
print(f"make zone (95%): tour {ps.make_zone_radius(ps.LAG_TOUR):.2f} ft, 90-golfer {ps.make_zone_radius(ps.LAG_AM90):.2f} ft")
make zone (95%): tour 3.17 ft, 90-golfer 2.11 ft

Use LAG_TOUR and LAG_AM90, not golfkit's default putter, for any pace or three-putt claim.

I.4.23 fitting — Chapter 23

Run a club fitting like an experiment: blocked hitting orders, comparisons with intervals, the winner's curse.

shots_to_detect(diff, sd, alpha=0.05, power=0.8) -> int;  shots_to_detect_sd_ratio(ratio, ...) -> int
winners_curse(n_configs, shots, sd, n_sims=20000, seed=0, margin=3.0) -> dict
from yardbook import fitting
print("shots per club setup to detect a 3-yd carry difference at SD 8 yd:", fitting.shots_to_detect(3.0, 8.0))
wc = fitting.winners_curse(n_configs=5, shots=10, sd=8.0, seed=23)   # five identical heads
print(f"winner's curse, 5 identical heads x 10 shots: best looks {wc['mean_best_minus_true']:.1f} yd better than it is")
shots per club setup to detect a 3-yd carry difference at SD 8 yd: 112
winner's curse, 5 identical heads x 10 shots: best looks 2.9 yd better than it is

(SIMULATED, seed 23.)

I.4.24 driver — Chapter 24

Fit the driver to the golfer, price each lever, and test whether a new driver really helped.

driver_payoff(delivery, attacks=(0.0, 3.0), extra_mph=(5.0,), speed_pct=(0.015,), both=((5.0, 0.0),), ground=None) -> DataFrame
rounds_to_detect(strokes_per_round, score_sd, power=0.8, alpha=0.05, sided=1) -> int
from yardbook import driver
a = impact.amateur_delivery(handicap=18.9).smash_a
walt = impact.Delivery("Driver", 88.0, -5.0, 12.0, spin_k=126.2, smash_a=a, label="Walt")
print(driver.driver_payoff(walt)[["lever", "carry", "total", "d_carry", "d_total"]].round(1).to_string(index=False))
                            lever  carry  total  d_carry  d_total
                            today  178.7  219.5      0.0      0.0
         best loft at attack -5.0  181.7  215.5      3.0     -4.0
           attack +0.0, best loft  192.1  228.5     13.4      9.0
           attack +3.0, best loft  198.0  236.0     19.3     16.5
            +5 mph, same delivery  195.8  234.0     17.1     14.6
       +1.5% speed, same delivery  183.3  223.4      4.7      4.0
+5 mph and attack +0.0, best loft  207.6  244.7     28.9     25.3

(MODEL, sea level, calm.) This is the dashboard's own driver call.

I.4.25 gapping — Chapter 25

Your iron and wedge ladder: gaps, overlap flags, wedge-loft planning and what gaps cost.

gap_report(distance_matrix, carry_col='carry_median', sd_col='carry_sd', club_col='club', overlap_max=0.25, hole_factor=1.5, compressed_factor=0.5) -> DataFrame
from yardbook import gapping, distances
sess = distances.simulate_range_session(distances.amateur_bag(88.0), n_per_club=30, seed=25)
gr = gapping.gap_report(distances.distance_matrix(sess))
print(gr[["club", "next_club", "carry", "next_carry", "gap", "overlap", "flag"]].head(4).round(2).to_string(index=False))
  club next_club  carry  next_carry   gap  overlap       flag
Driver    3-wood 180.12      150.14 29.97     0.03       hole
3-wood    5-wood 150.14      141.97  8.17     0.32 compressed
5-wood    Hybrid 141.97      131.58 10.39     0.24         ok
Hybrid    4-iron 131.58      127.52  4.06     0.38 compressed

(SIMULATED range session, seed 25.) On-course data needs sd_col=None (I.8).

I.4.26 ball_fit — Chapter 26

Test golf balls like an experiment and price the result in strokes.

shots_needed(effect, sd, design='independent', rho=0.0, power=0.8, alpha=0.05) -> int
from yardbook import ball_fit
print("shots per ball to detect a 2-yd carry difference at SD 6 yd:", ball_fit.shots_needed(2.0, 6.0))
print("  ... paired shots, correlation 0.5:", ball_fit.shots_needed(2.0, 6.0, design="paired", rho=0.5))
shots per ball to detect a 2-yd carry difference at SD 6 yd: 142
  ... paired shots, correlation 0.5: 71

I.4.27 practice — Chapter 27

Spend practice hours where they buy the most strokes (the gap model), and turn a plan into a range session.

allocate_practice(sg_report, hours=20.0, rates=None, levers=None, step=1.0, ...) -> DataFrame   # .attrs["total_gain"]
plan_value(plan_hours, sg_report, ...) -> DataFrame;  approach_bands(shots, baseline, bands=(...), labels=(...)) -> DataFrame
from yardbook import practice, sg_report
alloc = practice.allocate_practice(sg_report.category_report(rosa, sim12).loc[["OTT", "APP", "ARG", "PUTT"]], hours=20)
print(alloc[["sg", "gap", "hours", "expected_gain"]].round(2).to_string())
print("priced gain:", round(alloc.attrs["total_gain"], 2), "strokes per round (🧪 r = 0.03 per hour)")
            sg   gap  hours  expected_gain
category                                  
OTT      -0.59  0.59    0.0            0.0
APP      -3.29  3.29   20.0            1.5
ARG      -0.24  0.24    0.0            0.0
PUTT      0.28  0.00    0.0            0.0
priced gain: 1.5 strokes per round (🧪 r = 0.03 per hour)

Price against your target level, as here (Chapter 30's finding).

I.4.28 progress — Chapter 28

A personal round database (SQLite), control charts, and honest before-and-after tests.

RoundDB(path=':memory:')                            # add rounds and shots, query them back
improvement_test(before, after, lower_is_better=True, planned_effect=None, sd=None, looks=1, ...) -> dict
round_sd_for(handicap) -> float;  rounds_to_detect(effect, handicap=None, sd=None, power=0.8, alpha=0.05, sided=1) -> int
from yardbook import progress
print("round SD at 15.4:", progress.round_sd_for(15.4), "| rounds to detect 1.50:", progress.rounds_to_detect(1.50, 15.4))
round SD at 15.4: 4.7876 | rounds to detect 1.50: 126

Amateur round SDs are SIMULATED; TOUR_ROUND_SD = 2.756 is REAL. This is the report's "Prove" box.

I.4.29 handicap — Chapter 29

The World Handicap System applied to your own rounds: net double bogey, Score Differentials, the best 8 of 20, Course and Playing Handicaps.

Tee(name, course_rating, slope, par);  MEMBER_TEE      # the member course, CR 70.8 / Slope 125 🧪
posting_record(shots, course, index=None, pcc=0.0, dynamic=False, with_index=True) -> DataFrame
course_handicaps(index, tees, allowances=(...)) -> DataFrame;  net_head_to_head(golfer_a, golfer_b, course, ...) -> dict
from yardbook import handicap
rec = handicap.posting_record(rosa, holes.demo_course("member"), index=15.4)
print(rec[["round_id", "gross", "course_handicap", "ags", "differential", "index_after"]].tail(3).round(1).to_string(index=False))
 round_id  gross  course_handicap  ags  differential  index_after
       18     81               16   81           9.2         14.3
       19     93               16   89          16.5         14.6
       20     89               16   89          16.5         14.9

(SIMULATED.) ags is the score after net double bogey. No 0.96 multiplier.

I.4.30 benchmarks — Chapter 30

What separates one handicap level from the next, and where you stand against typical golfers of your level on the same course.

level_norms(levels=(0, 5, ..., 30), course='member', n=1000, seed=2026, baseline='pga') -> DataFrame
compare_to_level(sg_report, handicap, target=None, norms=None, step=5.0) -> DataFrame;  level_plan(comparison, ...) -> DataFrame
from yardbook import benchmarks
norms = benchmarks.level_norms(levels=(10, 15))                 # 1,000 rounds each, seed 2026
print(norms[["OTT", "APP", "ARG", "PUTT", "TOTAL", "score"]].round(2).to_string())
       OTT    APP   ARG  PUTT  TOTAL  score
h                                          
10.0 -3.23  -7.99 -2.75 -3.06 -17.02  86.11
15.0 -4.45 -11.00 -3.96 -3.96 -23.37  92.45

(SIMULATED, against the PGA TOUR baseline.) The dashboard subtracts these for its peers column.

I.4.31 tour_data — Chapter 31

A PGA TOUR player database and season tables from the free ESPN data, with safe merges and an audit.

canonical_sg(include_bad_par=True) -> DataFrame;  modelling_events(include_bad_par=True) -> DataFrame
player_database(sg=None) -> DataFrame;  player_season_table(year=None, sg=None, min_rounds=1, with_stats=True) -> DataFrame
from yardbook import tour_data
st = tour_data.player_season_table(2025)
print(st[["name", "rounds", "events", "sg_per_round", "sd", "lo95", "hi95", "wins"]].head(3).round(2).to_string(index=False))
             name  rounds  events  sg_per_round   sd  lo95  hi95  wins
Scottie Scheffler      84      21          3.29 2.35  2.79  3.80     6
Bryson DeChambeau      14       4          2.48 3.48  0.66  4.31     0
     Rory McIlroy      58      15          2.29 2.82  1.56  3.01     3

(REAL, field-adjusted SG: Total.) Fourteen rounds give an interval 3.6 strokes wide.

I.4.32 ratings — Chapter 32

Player skill ratings: decay-weighted, Bayesian-shrunk and Elo, with a printable rating card.

build_ratings(sg=None, as_of=None, half_life_rounds=40.0, form_rounds=16, active_days=365, ...) -> DataFrame
rating_card(player, table) -> dict;  head_to_head(a, b, table, rounds=4, sigma=None) -> dict
from yardbook import ratings
table = ratings.build_ratings()          # every active player, as of the data's last date
print(ratings.rating_card("Scottie Scheffler", table)["text"])
Scottie Scheffler — rating card as of 2026-11-23
  Bayes skill      +2.88 SG/round  (95% interval +2.09 to +3.68)
  rank             1 of 638 active players
  evidence         631 rounds, effective n 115.4
  ...

(REAL; trimmed.) ratings.rounds_needed(0.5) returns 117: it sizes an interval, not a test of change.

I.4.33 course_fit — Chapter 33

Course fit and course history, tested out of sample.

fit_dataset(refresh=False) -> DataFrame;  add_terms(df, k=5.0) -> DataFrame;  course_table() -> DataFrame
walk_forward(df, features, test_years, train_start=2006, baseline_features=None, n_boot=300, seed=0) -> dict
from yardbook import course_fit
print(course_fit.course_table().head(3).round(2).to_string(index=False))
course_id                           course_name  events  first  last  yards  par  n_par5  long_share
       21            Augusta National Golf Club      23   2004  2026 7445.0   72     4.0        0.63
       18 Arnold Palmer's Bay Hill Club & Lodge      23   2004  2026 7419.0   72     4.0        0.45
        3       TPC Scottsdale (Stadium Course)      23   2004  2026 7261.0   71     3.0        0.45

(REAL.) walk_forward shows Chapter 33's result: course fit adds almost nothing out of sample.

I.4.34 forecast — Chapter 34

Tournament forecasts by simulation, live in-event updates, and a calibration report card.

find_event(name, year) -> str;  forecast_event(event_id, n_sims=10000, seed=None, params=None, widen=True) -> DataFrame
favourite_summary(wf) -> dict;  wilson(k, n, z=1.959964) -> tuple;  live_forecast(event_id, after_round=3, ...) -> DataFrame
from yardbook import forecast
p, lo, hi = forecast.wilson(19, 133)
print(f"favourite won 19 of 133: {p:.3f} (Wilson 95% {lo:.3f} to {hi:.3f})")
print("2026 Masters event id:", forecast.find_event("Masters", 2026))
favourite won 19 of 133: 0.143 (Wilson 95% 0.093 to 0.212)
2026 Masters event id: 401811941

Keep widen=True, the absent-player correction.

I.4.35 majors — Chapter 35

How hard the four majors play, which holes do the damage, and whether a "major gene" exists.

major_events() -> DataFrame;  event_difficulty(sg=None, min_rounds=4) -> DataFrame
difficulty_summary(e=None, value='adj') -> DataFrame;  hole_difficulty(event);  stretch_cost(event_ids, holes=(11, 12, 13))
from yardbook import majors
print(majors.difficulty_summary()[["group", "events", "mean", "diff"]].round(2).to_string(index=False))
                     group  events  mean  diff
                All majors      90  2.20  2.39
                   Masters      23  1.76  1.95
          PGA Championship      22  1.82  2.01
                 U.S. Open      23  3.48  3.67
                  The Open      22  1.71  1.89
Regular, no opposite-field     770 -0.19  0.00

(REAL; field-adjusted to par per round, and the gap to regular events; one row trimmed.)

I.4.36 bets — Chapter 36

Prices, the bookmaker's margin, value, stake sizes, and how many bets it takes to prove an edge.

implied_probs(odds, fmt='decimal') -> ndarray;  market_overround(decimal_odds, target=1.0) -> float
matchup_prob(skill_a, skill_b, ..., sigma=2.756) -> dict;  bets_to_verify(decimal_odds, ev, z=1.96) -> int
from yardbook import bets
print("bets to verify a +5% edge at 21.0 (20/1):", f"{bets.bets_to_verify(21.0, 0.05):,}")
print("implied probabilities of 3.0 / 5.0 / 11.0:", bets.implied_probs([3.0, 5.0, 11.0]).round(3))
bets to verify a +5% edge at 21.0 (20/1): 32,189
implied probabilities of 3.0 / 5.0 / 11.0: [0.333 0.2   0.091]

I.4.37 dfs — Chapter 37

Daily fantasy golf: real fantasy points from hole scores, projections by simulation, and lineup building.

rules(site='DraftKings') -> dict;  score_events(event_ids, rule='DraftKings', ...);  round_points_table(years=None, ...) -> DataFrame
build_lineups(pool, n_lineups=1, objective='proj', salary_cap=50000, roster_size=6, ...) -> DataFrame
from yardbook import dfs
r = dfs.rules("DraftKings")
print({k: r[k] for k in ("salary_cap", "roster_size", "hole", "bogey_free")})
{'salary_cap': 50000, 'roster_size': 6, 'hole': {-3: 13.0, -2: 8.0, -1: 3.0, 0: 0.5, 1: -0.5, 2: -1.0, 3: -1.0}, 'bogey_free': 3.0}

(REFERENCE, data/reference/dfs_scoring.csv.) build_lineups needs SciPy 1.9+.

I.4.38 caddie_ai — Chapter 38

A prototype caddie assembled from the book's parts: today's conditions, tee plans, aim, lay-ups and putting pace.

recommend_shot(state, golfer, conditions=None, *, n=2000, seed=0, prefer_simple=0.0) -> dict;  say(rec) -> str
caddie_profile(golfer, putter=None, baseline=None, ...) -> dict;  hole_plan(golfer, hole, ...) -> dict
from yardbook import caddie_ai
rec = caddie_ai.recommend_shot({"hole": hole, "lie": "fairway", "distance": 160}, marcus, n=2000, seed=38)
print(caddie_ai.say(rec))
7i, hit it 162. Aim 14 yd left and 2 yd long of the flag. Expected 3.68 vs 4.08 for at the flag.

(SIMULATED golfer, MODEL recommendation, calm air.)

I.4.39 course_profile — Chapter 39

Course and hole difficulty from REAL tour scoring, a length model and its residuals, simulated course rating, and hazard experiments.

hole_difficulty_model(table=None, context=True, train_years=None, weight='n') -> DifficultyModel
course_report(course_id, model=None, years=None) -> dict;  event_difficulty(model, min_rounds=4) -> DataFrame
hazard_experiment(variants, golfers, n=20000, seed=3901, random_pins=True, cap_over=5) -> DataFrame
from yardbook import course_profile
cr = course_profile.course_report("21", model=course_profile.hole_difficulty_model())
sm = cr["summary"]
print(f"{sm['course_name']}: {sm['events']} events {sm['first']}-{sm['last']}, {sm['to_par_per_round']:+.3f} to par per round, "
      f"{sm['resid_per_round']:+.3f} beyond length; hardest hole {sm['hardest_hole']}")
Augusta National Golf Club: 23 events 2004-2026, +1.374 to par per round, -0.090 beyond length; hardest hole 11

(REAL.) The major flag absorbs Augusta's residual (Appendix K, Chapter 39 C4).

I.4.40 dashboard and cli — Chapter 40

The capstone: one call per report section, build_report to run them all, render_html to write the page, and the command line on top.

build_report(shots, handicap, name='You', target=None, course_rating=None, slope=None, change_after=None,
             driver=None, hours=20.0, aim_hole='water_right_approach_par4', aim_distance=160.0,
             n_boot=4000, seed=7, peers=None, note=None, source='your shot file') -> Report
render_html(rep, path, embed=True, note=None) -> Path;  report_figures(rep, note=None) -> dict
truth_check(rep, name) -> dict   # plus one function per report section
cli.build_parser() -> ArgumentParser;  cli.main(argv=None) -> int
from yardbook import dashboard, cli
rep = dashboard.build_report(rosa, 15.4, name="Rosa Delgado", note="SIMULATED - yardbook.cast, seed 154023")
tc = dashboard.truth_check(rep, "Rosa Delgado")
print(f"target {rep.target:g}; truth '{tc['expected']}'; found own {tc['found_own']} {tc['value_own']:+.2f}, "
      f"peers {tc['found_peers']} {tc['value_peers']:+.2f}, target {tc['found_target']} {tc['value_target']:+.2f}")
print("missing file -> exit", cli.main(["report", "--shots", "nope.csv", "--handicap", "12"]))
target 12; truth 'leak: APP'; found own APP -1.55, peers APP -2.20, target APP -3.29
error: no such file: nope.csv
missing file -> exit 2

Report keeps every table behind the page (rep.sg, rep.sub, rep.aim, rep.practice, rep.next, …). truth_check only means something for the cast. cli.main returns its exit code, which makes it easy to test.


I.5 How the modules fit together

05_dependency_map.py parses every module and lists which other yardbook modules it imports. Twenty-nine of the 42 modules import no other yardbook module, and every import points to an earlier chapter, so the package can be built and tested in book order. The connected modules (each line reads "imports"):

dashboard ─┬─ rounds (2)
           ├─ sg_report (11) ── sg_core (10)
           ├─ sg_deep (13)
           ├─ signal (14)
           ├─ aim (18)
           ├─ dispersion (19)
           ├─ driver (24) ── fitting (23), signal (14)
           ├─ gapping (25) ── distances (4), wedges (9)
           ├─ practice (27) ── sg_report (11)
           ├─ progress (28) ── rounds (2), sg_report (11), signal (14)
           ├─ handicap (29)
           └─ benchmarks (30) ── sg_report (11), signal (14)
cli ── dashboard (40), rounds (2), cast
importers (15) ── rounds (2)          ball_fit (26) ── strike (3), signal (14)
tee_strategy (21) ── legacy_stats (17)  dfs (37) ── forecast (34)
caddie_ai (38) ── aim (18), conditions (6), decisions (20), putting_strategy (22), tee_strategy (21)

The dashboard imports twelve modules, all from Chapters 2–30, and none of the tour modules, so it runs without the ESPN download. signal, rounds and sg_report are the hubs (imported by five, four and four modules): run the tests (I.7) after editing them. The tour modules read golfkit's REAL tables directly; only dfs builds on another.


I.6 Bringing your own data

yardbook reads no vendor's export directly, and this guide makes no claims about any product's format. importers defines one generic, start-only layout: one row per shot, saying where it was played from.

round_id, date, course, hole, par, hole_yards, shot_no, club, lie, distance, penalty_strokes, result
(optional: dist_to_green_edge, putts, first_putt)

Each shot's finish is read from the next row; the hole's last row is holed; result marks water or ob. Common words are normalised ("bunker" → sand, "trees" → recovery, "penalty area" → water, "Driver" → D). Three adapter templates come with the module: start_only (yards and feet), metric (illustrative column names, metres) and putts_summary (greens given as a putt count and first-putt length). Copy one and edit its column_map and units.

The workflow on a file with made-up column names (01_cli_and_schema.py, part 4; Rosa's SIMULATED rounds stand in for yours; output trimmed):

mine = {"round_id": "Round", "hole": "Hole", "par": "Par", "shot_no": "Shot", "club": "Club",
        "lie": "Lie", "distance": "Distance", "penalty_strokes": "Penalty", "result": "Result"}
shots = importers.from_generic_csv(TMP / "my_export.csv", column_map={v: k for k, v in mine.items()})
print(shots.attrs["validation"].summary())
shots.to_csv(TMP / "my_shots.csv", index=False)       # then: python -m yardbook report --shots my_shots.csv ...
 Round  Hole  Par  Shot Club     Lie   Distance  Penalty Result
     1     1    4     1    D     tee 401.501063        0    NaN
     1     1    4     2   5i   rough 177.689111        0    NaN
     1     1    4     3   LW fairway  28.698531        0    NaN
shots: 1,835 rows checked — 0 errors, 1 warnings
  warning distance_increase            1
  cast file (has start_edge_dist)    vs SIM 12: {'OTT': -0.59, 'APP': -3.29, 'ARG': -0.24, 'PUTT': 0.28, 'T2G': -4.12, 'TOTAL': -3.84}
  generic import (no edge distance)  vs SIM 12: {'OTT': -0.59, 'APP': -3.33, 'ARG': -0.21, 'PUTT': 0.28, 'T2G': -4.12, 'TOTAL': -3.84}
$ python -m yardbook report --shots <tmp>\my_shots.csv --handicap 15.4 --out <tmp>\mine.html --quick
wrote <tmp>\mine.html (20 rounds, 2 s)
  1. Practise: put 20 of your next 20 practice hours into approach
  2. Play: start recording where you aim
  3. Prove: log every round; judge the plan after about 124 rounds, not 5

The one warning is real golf: a shot that finished farther from the hole than it started. Warnings don't stop the report; errors do. With no distance to the green's edge, golfkit's 🧪 40-yard proxy moves about 0.04 strokes per round from around the green to approach, and the "Prove" number from 126 to 124 rounds, so add dist_to_green_edge if you can. With no aim_x, aim_y, the dispersion and aim sections are skipped ("needs aim coordinates") and the "Play" box asks you to record where you aim. The report never invents a column.

If you record only hole totals, importers.scorecard_approx_sg prices each hole from tee yardage and score, and each extra number you write down buys one more category (Chapter 15, §15.4).

When a file fails, report lists the errors and stops (part 5 breaks the template on purpose):

$ python -m yardbook report --shots <tmp>\bad.csv --handicap 15 --out <tmp>\bad.html
error: the shot file has validation errors (Chapter 2):
shots: 4 rows checked — 3 errors, 0 warnings
  error   bad_lie                      1
  error   chain_break                  1
  error   holed_flag                   1
[exit 2, 2 s]

rounds.validate_shots(df).issues lists the offending rows.


I.7 Testing

The end-to-end tests are in project/tests/test_yardbook_cli.py. From the book root:

python -m pytest project/tests -q
.....                                                                    [100%]
5 passed in 41.05s

They write Rosa's cast file with the command line, build her report and check its sections, charts, target of 12, −3.29 approach gap and WHS wording; check --images-beside and the driver model; check exit code 2 for a missing file; and check that truth_check recovers her approach leak. The toolkit has its own suite (python -m pytest toolkit/tests -q). python scripts/update_yardbook_init.py --check confirms every module imports and is in __all__:

modules found: 42  ·  added to __all__: 0
__init__.py already up to date
import yardbook: OK
import_module: 42/42 modules OK

A module of your own should have a docstring and an __all__, import only golfkit, the scientific stack and earlier modules, write only to paths it's given, and come with a test on a cast member, whose truth you know.


I.8 Known limits

The report states its own limits (Chapter 40, §40.8). These are the ones you'll meet.

  • The baseline isn't your course. SIMULATED baselines are built on generic holes, so a typical golfer of your level isn't zero by category on a real course. The peers column removes that effect, but exists only for the member course.
  • Baseline levels. dashboard.sim_baseline uses a cached SIMULATED table at your exact level if one exists (the cast levels are cached), else the nearest integer from −4 to 36. With no cache at all (a fresh copy of the book), golfkit builds the table once and saves it in data/processed/baselines/.
  • Handicap inputs. Off the member course, without --course-rating and --slope you get a neutral 🧪 72.0 / 113 and stroke indexes 1–18 in hole order.
  • On-course distances aren't carries. Gaps are flagged by size only (on-course spreads of 15–40 yards would make Chapter 25's overlap test flag every pair), and clubs are ordered by distance, not bag position, so an "inverted" pair can't appear. Gap on a launch monitor.
  • One demo hole. The aim calculator prices the water-right demo hole, not your course; course_profile.hazard_experiment handles your own holes.
  • The plan's gain is an assumption (🧪 3% of the remaining gap per hour, no published source). Use it to rank, not to forecast.
  • Small samples. Twenty rounds name the right category in 82% of fresh samples (SIMULATED, Chapter 40, §40.7), and sub-categories or close rankings much less often. Dispersion needs 15 full swings with a club, the aim calculator 12 approaches from 130–190 yards.
  • Without --change-after, the progress test is a noise check, and is labelled so.
  • Simulator quirks are left in place. Water drops replay with the same aim (rare blow-up holes); the approach multiplier also hits tee-shot 3-woods (tee_fix=True corrects it in tee_strategy, not in the cast's rounds); golfkit's targeting grid is lumpy at hazard lines, so yardbook searches by Monte Carlo. Fixing them would change every seeded number in the book.
  • ESPN publishes scores, not shots. Every category-level strokes-gained number here is SIMULATED; REAL numbers are SG: Total or published statistics.
  • Nothing here sees your lie, stance, the day's wind, firmness, nerves, or whether you committed to the target.