Distance by club from shots
Median distance for each club from a year of shots, next to the typical distance in your bag.
Each shot has the club it was played with and result.distance_yards, how far the ball went. This script collects a year of shots, takes the median distance per club, and prints it next to typical_total_yards from your bag.
Needs: a key with rounds:read and clubs:read, exported as NEW_JUNE_API_KEY.
#!/usr/bin/env bash
# distance-by-club.sh: needs curl, jq, and GNU or BSD date.
set -euo pipefail
since=$(date -u -v-365d +%Y-%m-%dT00:00:00Z 2>/dev/null || date -u -d '365 days ago' +%Y-%m-%dT00:00:00Z)
fetch_all() {
local base="$1" cursor="" page all="[]"
while :; do
local url="$base"
if [ -n "$cursor" ]; then url="$url&cursor=$cursor"; fi
page=$(curl -sf "$url" -H "Authorization: Bearer $NEW_JUNE_API_KEY")
all=$(jq -s '.[0] + .[1].data' <(echo "$all") <(echo "$page"))
if [ "$(echo "$page" | jq -r '.has_more')" != "true" ]; then break; fi
cursor=$(echo "$page" | jq -r '.next_cursor')
done
echo "$all"
}
shots=$(fetch_all "https://data.newjune.co/v1/shots?played_after=$since&limit=100")
clubs=$(fetch_all "https://data.newjune.co/v1/clubs?limit=100")
jq -rn --argjson shots "$shots" --argjson clubs "$clubs" '
($clubs | map({ (.club // "") : .typical_total_yards }) | add // {}) as $bag
| $shots
| map(select(.club != null and .club != "putter" and .is_provisional != true and .result.distance_yards != null))
| group_by(.club)
| map({ club: .[0].club, n: length, d: (map(.result.distance_yards) | sort) })
| sort_by(-(.d[(.n / 2 | floor)]))
| .[]
| "\(.club)\tshots: \(.n)\tmedian: \(.d[(.n / 2 | floor)] | round) yd\tbag: \($bag[.club] // "n/a")"'// distance-by-club.mts: Node 20+, no dependencies. Run with: npx tsx distance-by-club.mts
interface Shot {
club: string | null;
is_provisional: boolean | null;
result: { distance_yards: number | null };
}
interface Club {
club: string | null;
display_name: string;
typical_total_yards: number | null;
}
async function* listAll<T>(path: string, params: Record<string, string> = {}) {
let cursor: string | null = null;
do {
const url = new URL(`https://data.newjune.co/v1/${path}`);
url.searchParams.set('limit', '100');
for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value);
if (cursor) url.searchParams.set('cursor', cursor);
const response = await fetch(url, {
headers: { Authorization: `Bearer ${process.env.NEW_JUNE_API_KEY}` },
});
if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
const page = (await response.json()) as { data: T[]; has_more: boolean; next_cursor: string | null };
yield* page.data;
cursor = page.has_more ? page.next_cursor : null;
} while (cursor);
}
function median(values: number[]): number {
const sorted = [...values].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
}
const since = new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString();
const distances = new Map<string, number[]>();
for await (const shot of listAll<Shot>('shots', { played_after: since })) {
const yards = shot.result.distance_yards;
if (!shot.club || shot.club === 'putter' || shot.is_provisional || yards === null) continue;
distances.set(shot.club, [...(distances.get(shot.club) ?? []), yards]);
}
const bag = new Map<string, Club>();
for await (const club of listAll<Club>('clubs')) if (club.club) bag.set(club.club, club);
const rows = [...distances].map(([club, yards]) => ({ club, shots: yards.length, median: median(yards) }));
for (const row of rows.sort((a, b) => b.median - a.median)) {
const typical = bag.get(row.club)?.typical_total_yards ?? 'n/a';
console.log(`${row.club.padEnd(16)} shots: ${String(row.shots).padStart(3)} median: ${Math.round(row.median)} yd bag: ${typical}`);
}# distance_by_club.py: needs requests (pip install requests).
import os
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from statistics import median
import requests
API = "https://data.newjune.co/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['NEW_JUNE_API_KEY']}"
def list_all(path, **params):
params = {"limit": 100, **params}
while True:
response = session.get(f"{API}/{path}", params=params, timeout=30)
response.raise_for_status()
page = response.json()
yield from page["data"]
if not page["has_more"]:
return
params["cursor"] = page["next_cursor"]
since = (datetime.now(timezone.utc) - timedelta(days=365)).strftime("%Y-%m-%dT%H:%M:%SZ")
distances = defaultdict(list)
for shot in list_all("shots", played_after=since):
yards = shot["result"]["distance_yards"]
if not shot["club"] or shot["club"] == "putter" or shot["is_provisional"] or yards is None:
continue
distances[shot["club"]].append(yards)
bag = {club["club"]: club for club in list_all("clubs") if club["club"]}
rows = sorted(
((club, len(yards), median(yards)) for club, yards in distances.items()),
key=lambda row: row[2],
reverse=True,
)
for club, count, middle in rows:
typical = bag.get(club, {}).get("typical_total_yards") or "n/a"
print(f"{club:<16} shots: {count:>3} median: {round(middle)} yd bag: {typical}")driver shots: 84 median: 238 yd bag: 245
3_wood shots: 19 median: 214 yd bag: 220
7_iron shots: 46 median: 151 yd bag: 155
pitching_wedge shots: 38 median: 118 yd bag: 120Notes
- Median, not mean. One topped drive or one flier pulls an average a long way. The median shows your stock distance.
- One club only: filter on the server with
club, for examplelistAll('shots', { club: '7_iron', played_after: since }). The values are theclubenum in the shots reference. - Carry vs total:
result.distance_yardsis how far the ball traveled in total. Your bag'stypical_carry_yardsis carry only, so compare withtypical_total_yards. - Free-text context:
lie.type,planned.shot_type, andresult.qualityare free text (see Conventions). Group by them only after normalizing the values you care about, for example only shots whoselie.typementionsfairway. - Volume: a year of shots can be a few thousand items, which is a few dozen requests at
limit=100.